从模块方法调用super

时间:2011-09-19 17:34:01

标签: ruby ruby-on-rails-3 methods module 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,那么覆盖效果会很好,但是原来的方法没有被调用,我不希望这样。

2 个答案:

答案 0 :(得分:12)

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

module Foo
  class << self
    alias_method :original_foobar, :foobar
    def foobar
      puts "bar"
      original_foobar
    end
  end
end

答案 1 :(得分:6)

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

相关问题