Monday, October 1, 2007

Filters in RoR

Hi to all,

Filters enable you to write code in your controllers that wrap the processing
performed by actions—you can write a chunk of code once and have it be
called before or after any number of actions in your controller (or your controller’s
subclasses). This turns out to be a powerful facility. Using filters, we
can implement authentication schemes, logging, response compression, and
even response customization.

Rails supports three types of filter: before, after, and around.

before and after filters are invoked before or after
an action. Rails maintains two chains of filters for each controller. When a
controller is about to run an action, it executes all the filters on the before
chain. It executes the action before running the filters on the after chain.

eg: if u want to do the authentication for few files in ur app. Use this following code

put this code in ur applicaion.rb file of ur respective controller:

def authorize
unless User.find_by_id(session[:user_id])
flash[:notice] = "Please log in"
redirect_to(:controller => "login" , :action => "login" )
end
end

put the below in ur controller file. eg: name_controller.rb


class AdminController <>
end


using this filter u can protect each and every methods under this controller.

After Filter:

U can call this method after u executed any methods ( in ur controller ) like the below code:

class AdminController <>
before_filter :authorize
# ....
end


Around Filters

Around filters wrap the execution of actions. You can write an around filter in
two different styles. In the first, the filter is a single chunk of code. That code
is called before the action is executed. If the filter code invokes yield, the action
is executed. When the action completes, the filter code continues executing.
Thus, the code before the yield is like a before filter, and the code after the
yield is the after filter. If the filter code never invokes yield, the action is not
run—this is the same as having a before filter return false.



Example :

around_filter :one, :two
def one
logger.info("start one" )
yield
logger.info("end one" )
end
def two
logger.info("start two" )
yield
logger.info("end two" )
end

Output:

the sequence of log messages will be
start one
start two
. . .
end two
end one

No comments: