Filters are a convenient way to wrap actions and execute code before and/or after an action has been, or is being, processed. Before filters are executed before the action processing takes place. If any of the filters in the before filter chain returns false, processing is terminated and no other filters (or the action itself) are executed for that request. Likewise, the code within after filters is executed after the code within the action has been processed.
The main filters are before_filter, after_filter, and around_filter. When any one of them appears within a controller, its effect applies to all the actions within the current controller and its subclasses. As you can probably imagine, placing a filter within ApplicationController adds that filter to the chain of filters for all the actions in the application. All three filters accept the :only and :except options — which you should be familiar with by now — to limit the number of actions for which the filter should be applied.
These methods accept a method name as a symbol:
class ExampleController < ActionController::Base before_filter :authenticate #... private def authenticate #... end end
The method authenticate will be executed before any actions within ExampleController.
or a block:
class ExampleController < ActionController::Base after_filter do |controller|
# The action name is stored in controller.action_name #... end #... end
In addition, they even accept any class (an object in the case of the around ...