I'm trying to override a method located in a Gem in Ruby/Rails, and I'm struggling with some problems.
My开发者_JS百科 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.
You can do what you want like this:
module Foo
class << self
alias_method :original_foobar, :foobar
def foobar
puts "bar"
original_foobar
end
end
end
Calling super
looks for the next method in the method lookup chain. The error is telling you exactly what you are doing here: there is foobar
method in the method lookup chain for Foo
, since it is not inheriting from anything. The code you show in your example is just a redefinition of the Foo
module, so having the first Foo
does nothing.
精彩评论