Spec-Zone.ru › Ruby on Rails 6.0

модуль 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

  class_methods do
    ...
  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 # It works, now Bar takes care of its dependencies
end

Публичные методы экземпляров

class_methods(&class_methods_module_definition) Показать исходный код
# File activesupport/lib/active_support/concern.rb, line 163
def class_methods(&class_methods_module_definition)
  mod = const_defined?(:ClassMethods, false) ?
    const_get(:ClassMethods) :
    const_set(:ClassMethods, Module.new)

  mod.module_eval(&class_methods_module_definition)
end

Определяет методы класса из заданного блока. Вы также можете определять закрытые методы класса.

module Example
  extend ActiveSupport::Concern

  class_methods do
    def foo; puts 'foo'; end

    private
      def bar; puts 'bar'; end
  end
end

class Buzz
  include Example
end

Buzz.foo # => "foo"
Buzz.bar # => private method 'bar' called for Buzz:Class(NoMethodError)
included(base = nil, &block) Показать исходный код
# File activesupport/lib/active_support/concern.rb, line 129
def included(base = nil, &block)
  if base.nil?
    if instance_variable_defined?(:@_included_block)
      if @_included_block.source_location != block.source_location
        raise MultipleIncludedBlocks
      end
    else
      @_included_block = block
    end
  else
    super
  end
end

Вычисляет заданный блок в контексте базового класса, так что вы можете писать макросы классов здесь. Когда вы определяете более одного included блока, это вызывает исключение.

Вызывает метод суперкласса

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

Spec-Zone.ru

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