如果您在MyModuleA
的“正文”中包含MyModuleB
,那么它是模块本身可以用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
要注意的是,这不是一个很好的做法都没有。您可能会陷入包含模块的顺序之间的虚假依赖关系。 – geekazoid