O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.8. Filters

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required