Tuesday 26 November 2013

Alias and alias method chain

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 foowithfeature() method and add some extra functionality in foowithfeature method.

Now, I want to execute the foowithfeature() method by the calling foo() method. So I have create alias method as "aliasmethod :foo, :foowithfeature". 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 " aliasmethod :foo, :foowithfeature".

Now look to result when I call "Klass.new.foo"
It executes foowithfeature 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, foowithfeature(), and you end up with three methods: foo(), foowithfeature(), and foowithoutfeature().

alias_method_chain

Lets make it more simple with rails. "aliasmethodchain" 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 aliasmethodchain :foo, :feature and we will have 3 methods: foo, foowithfeature, foowithoutfeature 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
* http://apidock.com/ruby/Module/aliasmethod 
* http://ruby.about.com/od/rubyfeatures/a/aliasing.htm 
* http://apidock.com/rails/Module/aliasmethod_chain

No comments:

Post a Comment