如果您包含MyModuleB
在 的“正文”中MyModuleA
,则扩展了 B 的功能的是模块本身。如果您将它包含在included
块中,那么它将包含在混入的类中MyModuleA
。
那是:
module MyModuleA
extend ActiveSupport::Concern
include MyModuleB
end
产生类似的东西:
MyModuleA.send :include, MyModuleB
class Foo
include MyModuleA
end
尽管
module MyModuleA
extend ActiveSupport::Concern
included do
include MyModuleB
end
end
产生类似的东西:
class Foo
include MyModuleA
include MyModuleB
end
其原因ActiveSupport::Concern::included
类似于:
def MyModuleA
def self.included(klass, &block)
klass.instance_eval(&block)
end
end
块中的代码在included
包含类的上下文中运行,而不是在模块的上下文中运行。因此,如果 MyModuleB 需要访问它正在混入的类,那么您需要在included
块中运行它。否则,它实际上是同一件事。
通过演示:
module A
def self.included(other)
other.send :include, B
end
end
module B
def self.included(other)
puts "B was included on #{other.inspect}"
end
end
module C
include B
end
class Foo
include A
end
# Output:
# B was included on C
# B was included on Foo