Ruby 让超类方法在正确的命名空间中调用类
我有一些名称空间包含duck类型的类,它们都继承自Ruby 让超类方法在正确的命名空间中调用类,ruby,Ruby,我有一些名称空间包含duck类型的类,它们都继承自Base名称空间,如下所示: module Base class Client def self.greet puts Wrapper end def do_stuff puts Wrapper end end class Wrapper end end module Website class Client < Base::Client end c
Base
名称空间,如下所示:
module Base
class Client
def self.greet
puts Wrapper
end
def do_stuff
puts Wrapper
end
end
class Wrapper
end
end
module Website
class Client < Base::Client
end
class Wrapper < Base::Wrapper
end
end
Website::Client.greet
Website::Client.new.do_stuff
模块基座
类客户端
自我问候
放包装纸
结束
做什么
放包装纸
结束
结束
类包装器
结束
结束
模块网站
类Client
---输出---
Base::Wrapper
Base::Wrapper
我希望上面的代码打印(并引用)Website::Wrapper,有没有办法通过更改继承结构来实现这一点?如果名为
Wrapper
的常量位于顶级命名空间中,您可以编写::Wrapper
来引用它,但通常只编写Wrapper
就足够了
在Website::Client中,如果我尝试调用另一个类,如
包装器,它将调用Base::Wrapper
我没有看到:
module Base
class Client
end
class Wrapper
end
end
module Website
class Wrapper < Base::Wrapper
end
class Client < Base::Client
p Wrapper #=>Website::Wrapper
def self.greet #Create class method
p Wrapper #=>Website::Wrapper
end
def do_stuff
p Wrapper #=>Website::Wrapper
end
end
end
Website::Client.greet
Website::Client.new.do_stuff
--output:--
Website::Wrapper
Website::Wrapper
Website::Wrapper
模块基座
类客户端
结束
类包装器
结束
结束
模块网站
类包装器网站::Wrapper
def self.greet#创建类方法
p Wrapper#=>网站::Wrapper
结束
做什么
p Wrapper#=>网站::Wrapper
结束
结束
结束
网站::Client.greet
网站::Client.new.do_stuff
--输出:--
网站::包装器
网站::包装器
网站::包装器
您能否修改该示例以显示您遇到的问题
对修改后问题的回答:
这只是坏习惯吗
调用Base::Client.greet并获取网站::Wrapper会不会令人惊讶
有没有一种简单的方法可以让在子类中调用的方法默认为
那个类的名称空间
你这是什么意思?Website::Client的singleton类中未定义名为greet的类方法。如果要覆盖Base::Client.greet,可以这样做
另外,当您调用Website::Client.greet时,您正在编写Website::Client,因此您已经知道方法调用来自哪个类……但是在Base::Client.greet中,您可以添加行
put self
,这将标识调用该方法的对象,哪一个是类Website::Client。不清楚您在哪些名称空间中使用了Wrapper
。很抱歉,我已经编辑了代码示例以使其更加完整。您还应该删除以下行,因为它显然不是您正在做的:。。。如果我试图调用另一个类,例如Wrapper。
这就是你正在做的:网站::Client.greet网站::Client.new.do_stuff
…那么你在网站::Client中的什么地方“调用Wrapper”?这是我的问题的一个更清晰的布局,我复制了这个布局并在上面发布了更清晰的描述,谢谢!在这种情况下,收到Website::Wrapper会令人惊讶,但这正是我试图避免的。我基本上是试图避免覆盖具有完全相同逻辑的方法(包括名称空间的类名)。我想我可以通过定义一个名称空间常量来解决这个问题。