Home > Uncategorized > Aliasing a Method

Aliasing a Method

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.

Author: Abdul Basit Munda Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.

Spam Protection by WP-SpamFree