Aliasing a Method
May 1st, 2010
In Ruby, aliasing a method is a very cool way of overriding a method, but still having the ability to call the original, overrided method. For example:
if you have a global filter defined in the ApplicationController called authenticate :
class ApplicationController < ActionController::Base
before_filter :authenticate;
def autenticate
authenticate_user();
end
end
and you wanted to make a small change to that authenticate filter for the HelloController, we can use an alias_method(new_name, old_name) to achieve that:
class HelloController < ApplicationController
alias_method orig_authenticate, authenticate
def authenticate
do_some_extra_stuff();
# Call original authenticate method
orig_authenticate();
end
end
This is very useful in occasions, where you would like to override a method, but still want to access the overridden methods.