我试图覆盖位于 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,覆盖工作得很好,但是原始方法不会被调用,我不希望这样。
最佳答案
你可以像这样做你想做的事:
module Foo
class << self
alias_method :original_foobar, :foobar
def foobar
puts "bar"
original_foobar
end
end
end
关于ruby - 从模块方法调用 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7474912/