Thursday, November 10, 2016

alias_method in Ruby

alias_method(new_name, old_name)

Makes new_name a new copy of the old_name method. This is used to retain access to methods that are overridden.

module Tester
  alias_method :original_exit, :exit

  def exit(code=0)
    puts "Exiting with code #{code}"
    original_exit(code)
  end
end

include Tester
exit(99)
This prints: Exiting with code 99

This can be rewritten in a simpler way with less code like this:

module Tester  
  def exit(code=0)
    puts "Exiting with code #{code}"
    super
  end
end

include Tester
exit(99)

This also prints the same output. What is the use of alias_method? Here is a test case:

module Tester  
  def exit(code=0)
    puts "Exiting with code #{code}"
    super
  end
end

class Dummy
  include Tester
  def exit
    puts "Inside original exit"
  end  
end

Dummy.new.exit(99)
 
This fails with error message: ArgumentError: wrong number of arguments (given 1, expected 0). We can fix this by doing this:
module Tester  
  alias_method :original_exit, :exit

  def self.included(base)
    base.class_eval do
      def exit(code=0)
        puts "Exiting with code #{code}"
        original_exit
      end      
    end
  end
end
class Dummy
  include Tester
end
Dummy.new.exit(99)
 This also prints: Exiting with code 99. This explains when to use alias_method, use it only when it is needed.


No comments:

Post a Comment