Filters

Introduction

before_filter Example


class UsersController < ApplicationController
  before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge]

  private
  def admin_required
    if !logged_in_as_admin?
      flash[:notice] = "You need to be admin to access that page" 
      session[:return_to] = request.request_uri
      redirect_to login_path
    end
  end
end

before_filter: Inheritance, Skipping, and Ordering


class ApplicationController < ActionController::Base
  before_filter :log_session, :set_locale
end

class ArticlesController < ApplicationController
  skip_filter :log_session, :only => [:rss]
  prepend_before_filter :initialize_article_session
end

after_filter


class NewspaperController < ActionController::Base
   after_filter :compress_response

   def compress_response
    self.response.body = compress(response.body)
   end
end

around_filter


class BlogController < ApplicationController 
  around_filter :time_an_action

  def time_an_action 
    started = Time.now 
    yield 
    elapsed = Time.now - started 
    logger.info("#{action_name} took #{elapsed} seconds") 
  end 
end

Filter Blocks


around_filter do |controller, action| 
  started = Time.now 
  action.call 
  elapsed = Time.now - started 
end 

Filter Classes


class TimingFilter 
  def self.filter(controller) 
    started = Time.now 
    yield 
    elapsed = Time.now - started 
  end 
end 

around_filter TimingFilter

Verification


verify :params => "admin_privileges", :xhr => true,
  :only => :update_post, :redirect_to => { :action => "settings" }

verify :method => :post,
  :only => [:destroy, :create, :update],
  :redirect_to => {:action => :list}