alias_method
This method creates the alias(duplicate name) of the method
class Klass
def a
puts "alphabates"
end
alias_method :b, :a
end
Klass.new.a
=> alphabets
Klass.new.b
=> alphabets
Now, lets see the actual usage of alias_method
class Klass
def foo
puts "Inside foo"
end
def foo_with_feature
puts "Calling Method..."
foo_without_feature
puts "... Method Called"
end
alias_method :foo_without_feature, :foo
alias_method :foo, :foo_with_feature
end
Klass.new.foo
=> Calling Method...
Inside foo
...Method Called
Klass.new.foo_without_feature
=> Inside too
In above code, I have defined the class with foo() method. Later I have think of extending the foo() method. So I have created the foo_with_feature() method and add some extra functionality in foo_with_feature method.
Now, I want to execute the foo_with_feature() method by the calling foo() method. So I have create alias method as "alias_method :foo, :foo_with_feature". But at the same time, I doesn't want to loose the contact to original foo method. So, I have created another alias method as " alias_method :foo, :foo_with_feature".
Now look to result when I call "Klass.new.foo"
It executes foo_with_feature method which internally call original foo method. So, thereby we have achieve our goal of extending the original method without replacing its actual call method.
In other words, you provide the original method, foo(), and the enhanced method, foo_with_feature(), and you end up with three methods: foo(), foo_with_feature(), and foo_without_feature().
alias_method_chain
Lets make it more simple with rails. "alias_method_chain" reduces the override to write two aliases with single line.
Note : Test below code in rails console
class Klass
def foo
puts "Inside foo"
end
def foo_with_feature
puts "Calling Method..."
foo_without_feature
puts "... Method Called"
end
alias_method_chain :foo, :feature
end
So now we can just type alias_method_chain :foo, :feature and we will have 3 methods: foo, foo_with_feature, foo_without_feature which are properly aliased as describe above
This kind of things are used in monkeypatching, support to previous version of gem, plugin where you extend the some method of class, catch the method call of that class, do some extra and continue with the original method execution.
References