1

我有一个类层次结构如下:

class Tree
  def initialize(id, value)
    @id, @value = id, value
  end
end

class Entity < Tree

  include Mongoid::Document

  def initialize(id, value)
    # Do some stuff...
    super(id, value)
  end

end

但是,在方法super内部调用会调用位于 中的方法,而不是父类中的方法。Entity#initializeinitializeMongoid::DocumentTree

包含模块后,如何Tree#initialize从 的主体调用该方法?Entity#initializeMongoid::Document

4

1 回答 1

4

这就是 Ruby 的工作原理。当您包含一个 Module 时,ruby 隐式创建一个匿名类并将其放在方法查找队列中的 current 之上。

呼叫Entity.ancestors也会显示Mongoid::Document在列表中。

我可以推荐一本好书:Metaprogramming RubybyPaolo Perotta

另外这里是一个类似主题的论坛帖子,解释了超级东西

更新:

如果避免调用模块构造函数是你想要的,这是一个可能的技巧

class Entity < Tree

  def initialize(id, value)
    # Do some stuff...
    # initialize first
    super(id, value)
    # and after that - extend
    extend Mongoid::Document
  end

end

此方法未在模块上运行 self.included。如果您需要保留此功能,但仍不运行模块的初始化程序,则可以在 init 中使用 eigenclass:

class Entity < Tree

  def initialize(id, value)
    # Do some stuff...
    # initialize first
    super(id, value)
    # and after that - include into eigenclass
    class << self
      include Mongoid::Document
    end
  end

end
于 2012-05-30T19:41:45.563 回答