如果您在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