ruby - 当初始化被包含的模块覆盖时调用父构造函数

标签 ruby mongodb mongoid

我的类层次结构如下:

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

但是,在 Entity#initialize 方法内调用 super 会调用位于 Mongoid::Document 中的 initialize 方法>,而不是父类Tree中的那个。

Mongoid::Document 模块完成之后,如何从 Entity#initialize 的主体中调用 Tree#initialize 方法包括在内?

最佳答案

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

同时调用Entity.ancestors将在列表中显示Mongoid::Document

我可以推荐一本很棒的书:Metaprogramming Ruby,作者:Paolo Perotta

还有a forum thread on a similar topic explaining super stuff

更新:

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

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 中使用特征类:

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

关于ruby - 当初始化被包含的模块覆盖时调用父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822151/

相关文章:

ruby - Mongoid 'or' 和 'in' - 查询多个数组

ruby - 使用 axlsx 创建 3 色条件格式

ruby - 积极的前瞻不会在第一次出现时停止

ruby - Ruby 中标签的递归缩进

scala - 如何使用 MongoListField 返回列表

ruby-on-rails - 数组的未定义方法 `serializable_hash'

ruby-on-rails - 具有多态关联的范围和查询

php - 如何使用 php 处理 mongoDB 中的 "datetime"?

javascript - 蒙戈 : Limit returned records to an incremental count on slice

mongodb - MongoDB中的集合ID长度