alias_method_chain和猴子补丁

时间:2012-11-19 18:37:18

标签: ruby

我想修补为alias_method_chain创建的方法,但不会调用覆盖的方法

# foo.rb
require 'active_support/core_ext'

class Foo
  def foo
    "original foo"
  end

  def foo_with_flag
    "foo with flag"
  end

  alias_method_chain :foo, :flag
end

# foo_ext.rb
class Foo
  def foo_with_flag
    "overridden foo with flag"
  end
end

foo = Foo.new
foo.foo # => "foo with flag"
foo.foo_with_flag # => "overridden foo with flag"

如何让Foo#foo使用Foo#foo_with_flag的最后一次实现?

1 个答案:

答案 0 :(得分:2)

第一个alias_method_chain执行alias_method :foo, :foo_with_flag(第一个定义的副本),当您重新定义foo_with_flag :foo仍然是别名&# 39;编辑第一个定义。在第二个定义之后你必须再次alias_method :foo, :foo_with_flag(而不是"整个链")。