Spec-Zone.ru › Ruby on Rails 4.1

модуль ActiveSupport::Concern

Типичный модуль выглядит так:

module M
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  module ClassMethods
    ...
  end
end

Используя ActiveSupport::Concern вышеуказанный модуль можно переписать так:

require 'active_support/concern'

module M
  extend ActiveSupport::Concern

  included do
    scope :disabled, -> { where(disabled: true) }
  end

  module ClassMethods
    ...
  end
end

Кроме того, он корректно обрабатывает зависимости модулей. Учитывая Foo модуль и Bar модуль, который зависит от первого, обычно пишут следующее:

module Foo
  def self.included(base)
    base.class_eval do
      def self.method_injected_by_foo
        ...
      end
    end
  end
end

module Bar
  def self.included(base)
    base.method_injected_by_foo
  end
end

class Host
  include Foo # We need to include this dependency for Bar
  include Bar # Bar is the module that Host really needs
end

Но почему Host должен заботиться о зависимостях Bar, а именно Foo? Мы могли бы попытаться скрыть их от Host, напрямую включая Foo в Bar:

module Bar
  include Foo
  def self.included(base)
    base.method_injected_by_foo
  end
end

class Host
  include Bar
end

К сожалению, это не сработает, так как при включении Foo, его base — это Bar модуль, а не Host класс. С ActiveSupport::Concern, зависимости модулей разрешаются правильно:

require 'active_support/concern'

module Foo
  extend ActiveSupport::Concern
  included do
    def self.method_injected_by_foo
      ...
    end
  end
end

module Bar
  extend ActiveSupport::Concern
  include Foo

  included do
    self.method_injected_by_foo
  end
end

class Host
  include Bar # works, Bar takes care now of its dependencies
end

Открытые методы экземпляров

append_features(base) Показать исходный код
Вызывает метод суперкласса
# File activesupport/lib/active_support/concern.rb, line 111
def append_features(base)
  if base.instance_variable_defined?(:@_dependencies)
    base.instance_variable_get(:@_dependencies) << self
    return false
  else
    return false if base < self
    @_dependencies.each { |dep| base.send(:include, dep) }
    super
    base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
    base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block)
  end
end
included(base = nil, &block) Показать исходный код
Вызывает метод суперкласса
# File activesupport/lib/active_support/concern.rb, line 124
def included(base = nil, &block)
  if base.nil?
    raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block)

    @_included_block = block
  else
    super
  end
end

© 2004–2016 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API