gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:26 26 4
gpt4 key购买 nike

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

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 隐式地创建一个匿名类并将它放在方法查找队列中的当前之上。

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

我可以推荐一本很棒的书:Metaprogramming Ruby by 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。如果您需要保留此功能,但仍不运行模块的初始化程序,则可以在初始化中使用特征类:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com