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'
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With