Ruby’s alias_method

Today I learned about an interesting method in Ruby alias_method, this method can be used to refer to an old method in a module. The documentation is here: http://apidock.com/ruby/Module/alias_method. But at first glance, I couldn’t understand what it’s used for. So this simple post will illustrate a little.

Let’s say we have a module initially:

module Mod
  def print_asdf
    puts "lalalala"
  end
end

We can use it like this:

irb> include Mod
 => Object
irb> print_asdf
  lalalala

Later we decided to reopen the module and overwrite the function to add something:

module Mod
  def print_asdf
    print_asdf
    puts "changed"
  end
end

It’s just like calling the superclass method when we’re doing inheritance in OOP, but for this case we can’t use super.print_asdf, if we call the above method, we’ll run into error:

irb> include Mod
irb> print_asdf
SystemStackError: stack level too deep
   from /Users/tanjunrong/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/irb/workspace.rb:80
Maybe IRB bug!

That’s because it’s running recursively! This can be solved by alias_method:

module Mod
  alias_method :hey, :print_asdf

  def print_asdf
    hey
    puts "hehe"
  end
end

Now we can use it properly:

irb> include Mod
irb> print_asdf
  lalalala
  hehe

Simple post. Bye!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s