7

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

class Article < ActiveRecord::Base
  include DoubleIncludedModule
  include AModule

  # ...
end

module AModule
  include DoubleIncludedModule

  # ...
end

module DoubleIncludedModule
  # ...
end

DoubleIncludedModule课程中会包含多少次Article?也就是说,由于DoubleIncludedModule(首先在Article类中,然后在类本身中AModule包含Article)的“后续”包含,将是 Ruby 自动处理的“双重包含”问题,还是会DoubleIncludedModule(错误地)包含两次?

当然,我只想包含该DoubleIncludedModule模块一次。我怎样才能以正确的方式做到这一点(也许通过使用一些 Ruby on Rails 方法)?

4

1 回答 1

10

我会用一个例子来回答:

module A
  def self.included base
    puts "A included in #{base}"
  end
end

module B
  include A

  def self.included base
    puts "B included in #{base}"
  end
end

class C
  include A
  include B
end

p C.ancestors

印刷

A included in B
A included in C
B included in C
[C, B, A, Object, Kernel, BasicObject]

As we can see, A is included only once into C. Though technically it was included twice since it was included into B which was also included into C. Does this matter? Probably not. Each still only occurs once in the ancestor chain, and any methods would've been overridden with equivalent implementations—i.e., essentially a no-op. Unless you're doing something exotic with the included hook, you're unlikely to notice anything.

于 2012-09-26T05:13:02.107 回答