从模块方法调用 super
我正在尝试重写位于 Ruby/Rails 中 Gem 中的方法,但我遇到了一些问题。
我的目标是在调用 Gem 中的方法时执行自定义代码,同时继续执行原始代码。
我尝试将代码抽象为以下脚本:
module Foo
class << self
def foobar
puts "foo"
end
end
end
module Foo
class << self
def foobar
puts "bar"
super
end
end
end
Foo.foobar
执行此脚本会出现此错误:
in `foobar': super: no superclass method `foobar' for Foo:Module (NoMethodError)
我应该如何编写重写方法,以便我可以在引发此异常的情况下调用 super?
PS:如果我删除 super,重写工作得很好,但是原始方法不会被调用,我不希望这样。
I'm trying to override a method located in a Gem in Ruby/Rails, and I'm struggling with some problems.
My goal is to execute custom code when a method from the Gem is called, but also to keep executing the original code.
I tried to abstract the code into the following script:
module Foo
class << self
def foobar
puts "foo"
end
end
end
module Foo
class << self
def foobar
puts "bar"
super
end
end
end
Foo.foobar
Executing this script gives me this error:
in `foobar': super: no superclass method `foobar' for Foo:Module (NoMethodError)
How should I write the overriding method so I can call super with this exception being raised?
PS: The overriding works just fine if I remove the super, but then the original method isn't called and I don't want that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做自己想做的事:
You can do what you want like this:
调用 super 会在方法查找链中查找下一个方法。该错误准确地告诉您在这里做什么:在
Foo
的方法查找链中有foobar
方法,因为它不是从任何东西继承的。您在示例中显示的代码只是Foo
模块的重新定义,因此第一个Foo
没有任何作用。Calling
super
looks for the next method in the method lookup chain. The error is telling you exactly what you are doing here: there isfoobar
method in the method lookup chain forFoo
, since it is not inheriting from anything. The code you show in your example is just a redefinition of theFoo
module, so having the firstFoo
does nothing.