从模块方法调用super

Elh*_*lhu 5 ruby methods module super ruby-on-rails-3

我试图在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
Run Code Online (Sandbox Code Playgroud)

执行此脚本会给我这个错误:

in `foobar': super: no superclass method `foobar' for Foo:Module (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

我应该如何编写覆盖方法,以便在引发此异常时调用super?

PS:如果我删除超级,覆盖的工作就好了,但是原来的方法没有被调用,我不希望这样.

Tim*_*ott 14

你可以这样做你想做的事:

module Foo
  class << self
    alias_method :original_foobar, :foobar
    def foobar
      puts "bar"
      original_foobar
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是正确的答案 (2认同)
  • 你先生是英雄。谢谢你。 (2认同)

jer*_*son 7

调用super在方法查找链中查找下一个方法.错误告诉你你在这里做了什么:foobar方法查找链中有方法Foo,因为它不是从任何东西继承.您在示例中显示的代码只是对Foo模块的重新定义,因此让第一个代码Foo无效.