tags:

views:

85

answers:

2

Do you use the alias method in order to add more ways to call methods (like length and size) or is there another use for it?

+3  A: 

The alias_method call is also useful for re-implementing something but preserving the original version. There's also alias_method_chain from Rails which makes that kind of thing even easier.

alias_method also comes in handy when you have a number of behaviors that are initially identical but might diverge in the future, where you can at least rough them in to start.

def handle_default_situation
  nil
end

%w[ poll push foo ].each do |type|
  alias_method :"handle_#{type}_situation", :handle_default_situation
end
tadman
+3  A: 

Yes.

It is often used to preserve a handle to existing methods before overriding them. (contrived example)

Given a class like this:

class Foo
  def do_something
    puts "something"
  end
end

You could see code that adds new behaviour like so:

class Foo
  def do_something_with_logging
    puts "started doing something"
    do_something_without_logging # call original implementation
    puts "stopped doing something"
  end

  alias_method :do_something_without_logging, :do_something
  alias_method :do_something, :do_something_with_logging
end

(this is exactly how alias_method_chain works)

However, for this use case it't often more appropriate to use inheritance and modules to your advantage.

Still, alias_method is a useful tool to have, if you absolutely need to redefine behaviour in an existing class (or if you wanted to implement something like alias_method_chain)

levinalex