In case you ever forget the order of Ruby’s alias method.

by Rabbit

Think of it like this…

alias :new_method, :original_method

Create a new method called ‘new_method’, based on the contents of the method called ‘original_method’.

Example…

class Rabbit
 
  def eat
    puts "You eat a carrot."
  end
 
end
 
irb(main):008:0> Rabbit.new.eat
You eat a carrot.
class Rabbit
 
  def eat
    puts "You eat a carrot."
  end
 
  alias :eat_original :eat
 
end
 
irb(main):010:0> Rabbit.new.eat
You eat a carrot.
=> nil
irb(main):011:0> Rabbit.new.eat_original
You eat a carrot.
=> nil

You can now call both methods and they do the same thing, because they are copies.

class Rabbit
 
  def eat
    puts "You eat a carrot."
  end
 
  alias :eat_original :eat
 
  def eat
    puts "You eat celery."
    eat_original
  end
 
end
 
irb(main):015:0> Rabbit.new.eat
You eat celery.
You eat a carrot.

Now you have two methods, each one is different, but one calls the other, so we have just added functionality to the original method name without losing the original functionality.

The above technique is used a lot in Rails. (Although they have a helper called alias_chain_method, which I won’t go into here, but if you’re interested, Err has a good writeup.)

One more time, for posterity:

alias :new_method, :original_method

Create a new method called ‘new_method’, based on the contents of the method called ‘original_method’.

Now if anyone can tell me how to use alias with methods that end in a question mark I’d be happy!