简体   繁体   中英

alias_method_chain and monkey patching

I want to monkey patch a method created for alias_method_chain but the overwritten method is not called

# 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"

How can I make Foo#foo use the last implementation of Foo#foo_with_flag ?

The first alias_method_chain do the alias_method :foo, :foo_with_flag (a copy of the first definition), when you redefine foo_with_flag :foo is still alias'ed to the first definition. You have to do alias_method :foo, :foo_with_flag again after the second definition (not the "whole chain").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM