ruby - 从模块方法调用 super

标签 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,覆盖工作得很好,但是原始方法不会被调用,我不希望这样。

最佳答案

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

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/

相关文章:

ruby - 为什么规范失败?

ruby - 使用 gsub 在字符之间插入空格 - Ruby

c# - 命名空间不能直接包含字段或方法等成员吗?

ruby - 如何通过 ruby​​ UDPSocket 类发送原始十六进制数据?

ruby 守卫 : Is the directory being watched stored in some variable?

ruby-on-rails - Rails 4 JSON::ParserError (757: 'null' 处的意外标记):

c++ - 如何将成员函数传递给函数指针?

java - 在项目中使用不同的 Java 代码(如何访问变量)

ruby-on-rails - 限制mongoid中的版本属性

jquery - 复选框和 Ajax