理解“后续”mixin模块的`include`语句行为

时间:2012-09-26 04:53:08

标签: ruby-on-rails ruby module include

我试图在多个Mixins中使用时理解include语句行为。也就是说,我有这些陈述:

class Article < ActiveRecord::Base
  include DoubleIncludedModule
  include AModule

  # ...
end

module AModule
  include DoubleIncludedModule

  # ...
end

module DoubleIncludedModule
  # ...
end

DoubleIncludedModule课程中包含Article多少次?也就是说,由于DoubleIncludedModuleArticle类中的第一个,然后是AModule类本身所包含的Article中的“后续”包含)将是“双重包含“由Ruby自动处理的问题或DoubleIncludedModule(错误地)包括两次?

当然,我想只包含DoubleIncludedModule模块一次。我怎样才能以正确的方式实现(可能通过使用一些Ruby on Rails方法)?

1 个答案:

答案 0 :(得分:9)

我将回答一个例子:

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中。这有关系吗?可能不是。每个仍然只在祖先链中出现一次,并且任何方法都会被等同的实现覆盖 - 即,基本上是无操作。除非你用included钩子做一些异国情调,否则你不太可能注意到任何事情。