我的类层次结构如下:
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/