Alias ​​method chain method undefined

For some reason, my alias_method_chain doesn't want to work, and I have no idea why. Can someone explain to me why the following will not work?

[2] pry(main)> Client.respond_to? :mapping
=> true
[3] pry(main)> Client.alias_method_chain :mapping, :safety
NameError: undefined method `mapping' for class `Client'
+5
source share
2 answers

To get a chain of alias methods for an object of a certain class, you must call alias_method_chainthe class itself, not its instance. If you want to create a chain of class methods, the same rule applies: you must call alias_method_chainthe classton class, which can be obtained as follows:

klass = class << Client; self; end  # => returns singleton class for Client class

In this case, Clientis an instance of the class klass(which has the class Classas its superclass).

:

class Client
  def self.mapping
    puts 'mapping'
  end

  def self.mapping_with_safety
    puts 'safety'
    mapping_without_safety
  end

  class << self
    # call alias_method_chain in context of Client singleton class
    alias_method_chain :mapping, :safety
  end
end

# alternatively you can do it outside of Client class like that 
# (class << Client; self; end).alias_method_chain :mapping, :safety

Client.mapping
# => safety
# => mapping
+7

alias_method_chain, , , , Client.new.respond_to? :mapping ( ).

+2

All Articles