Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling super from module method

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.

like image 598
Elhu Avatar asked Sep 19 '11 17:09

Elhu


2 Answers

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
like image 52
Tim Scott Avatar answered Sep 24 '22 08:09

Tim Scott


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.

like image 30
jergason Avatar answered Sep 23 '22 08:09

jergason