我试图理解在多个Mixins中使用时的include语句行为.也就是说,我有这些陈述:
class Article < ActiveRecord::Base include DoubleIncludedModule include AModule # ... end module AModule include DoubleIncludedModule # ... end module DoubleIncludedModule # ... end
Article类中包含DoubleIncludedModule的次数是多少?也就是说,由于DoubleIncludedModule的“后续”包含(第一个在Article类中,然后在Article类本身包含的AModule中),将是Ruby自动处理的“双重包含”问题,或者包含DoubleIncludedModule(错误地)两次?
当然,我想只包含一次DoubleIncludedModule模块.我怎样才能以正确的方式实现(可能通过使用一些Ruby on Rails方法)?
解决方法
我将以一个例子回答:
module M def self.included base puts "M included in #{base}" end end module N include M def self.included base puts "N included in #{base}" end end class C include M include N end p C.ancestors
版画
M included in N M included in C N included in C [C,N,M,Object,Kernel,BasicObject]
正如我们所看到的,M只被包含在C中一次.虽然从技术上来说它被包括两次,因为它被包含在N中,它也包含在C中.这有关系吗?可能不是.每个仍然只在祖先链中出现一次,并且任何方法都会被等同的实现覆盖 – 即,基本上是无操作.除非你用包括钩子做一些异国情调,否则你不太可能注意到任何东西.