如果你包括MyModuleB
在“身体”中MyModuleA
,那么模块本身就扩展了 B 的功能。如果您将其包含在included
块,然后将其包含在混合的类中MyModuleA
.
That is:
module MyModuleA
extend ActiveSupport::Concern
include MyModuleB
end
产生类似的东西:
MyModuleA.send :include, MyModuleB
class Foo
include MyModuleA
end
while
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