Sha256: 9d51e22929c45930bfd84a41fb175b1c960746c5f0be672d3e37c02a5a487e2c

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

module ResourceDefaults
  class Railtie < Rails::Railtie
    initializer 'resource_defaults.load', :before => 'action_dispatch.prepare_dispatcher' do
      ActionDispatch::Routing::Mapper.send :include, ResourceDefaults
      ActionDispatch::Routing::Mapper.extend ResourceDefaults::ClassMethods
    end
  end

  module ClassMethods
    def new(*args)
      object = super
      object.initialize_resource_defaults
      object
    end
  end

  def initialize_resource_defaults
    @scope[:resource_defaults] = {}
    @scope[:resource_defaults_in_progress] = []
  end

  def resource_defaults(*args, &block)
    options = args.extract_options!
    target = args.first
    raise ArgumentError, 'must provide a resource to apply default actions' if target.blank?
    @scope[:resource_defaults][target] = options.merge(:block => block)
  end

  def scope(*args)
    old_resource_defaults = @scope[:resource_defaults].dup
    super
  ensure
    @scope[:resource_defaults] = old_resource_defaults
  end

  private

  def apply_common_behavior_for(method, resources, options, &block)
    return true if super

    resource = resources.first
    if !@scope[:resource_defaults_in_progress].include?(resource) && @scope[:resource_defaults][resource]
      defaults = @scope[:resource_defaults][resource].dup
      scope :resource_defaults_in_progress => resource do
        default_block = defaults.delete(:block)
        send method, resource, options do
          instance_exec &default_block if default_block
          instance_exec &block if block
        end
      end
      return true
    end

    false
  end

  def merge_resource_defaults_in_progress_scope(parent, child)
    (parent || []) + [child]
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
resource_defaults-1.0.2 lib/resource_defaults.rb