Generally whenever a request comes to the controller, controller invokes the requested action and send the response back to the view, but sometimes we need some actions(authentication) to be executed before or after the action is called, in that case we need to apply the filters in controller. So we can say that filters are methods that run before, after or around a controller's action.
There are three types of filters implemented in Rails:
- before_filter
- after_filter
- around_filter
before_filter: Before filters are the methods that run before the controller action, Mostly it is used to prevent unauthorized access to controller actions but it can also be used to load database records.
For Example:
class HomeController < ApplicationController
before_filter :login_required
def login_required
// check weather the user is logged in or not
end
def index
end
end
In the above example we need to check if the user is logged in only then it can invoke index action so we have defined login_required method as before filter,now if a request comes for index action, then first it will execute login required and then it will call index action.
after_filter: After filters are the methods that run after the controller action is completed,if there is some logic that we need to run after running a set of actions, then an after filter is a good place to keep that logic.Generally after filters are used for logging.
For Example:
class HomeController < ApplicationController
after_filter :update_recored
def update_recored
// update the record
end
end
Around filters: Sometimes we have some logic that need to execute before and after the action being run. In that case around filter is used.It simply yields to the action in whatever place is necessary.We can use around filters for exception handling etc.
For Example
class HomeController < ApplicationController
around_filter :catch_exception
def catch_exception
begin
yield
rescue
render text: "It broke!"
end
end
end
Wherever yield is called, the action will be executed. So the functionality here could recover from any exception that occurs in the yielded action.
So we have seen filters enable controllers to run pre and post processing code for its actions. These filters can be used to do authentication, caching, or auditing before or after the intended action is performed. Filters have access to the request, response, and all the instance variables set by other filters in the chain.
Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.
0 Comment(s)