Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias method chain undefined method

For some reason my alias_method_chain doesn't want to work and I have no idea why. Can anyone explain to me why the following won't 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'
like image 613
Robert Ross Avatar asked Jan 04 '12 19:01

Robert Ross


Video Answer


2 Answers

To get alias method chain for object of some class you should call alias_method_chain on class itself and not on its instance. If you want to make chain of class methods the same rule applies: you should call alias_method_chain on class's singleton class that can be obtained like that:

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

In that case Client is an instance of klass class (that has Class class as its superclass).

Resulting example of class methods chain can be the following:

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's 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
like image 71
KL-7 Avatar answered Sep 20 '22 22:09

KL-7


In order for alias_method_chain to work, the mapping function must be an instance method, not a class method like in your example, so Client.new.respond_to? :mapping needs to be true (notice the new call).

like image 43
clyfe Avatar answered Sep 19 '22 22:09

clyfe