method

before_filter

Importance_5
v1.2.6 - Show latest stable - 9 notes - Class: ActionController::Filters::ClassMethods
before_filter(*filters, &block) public
Register or log in to add new notes.
July 23, 2008 - (<= v2.1.0)
10 thanks

:only, :except and passing in multiple parameters

To specify that the filter should be applied to or excluded from given controller actions, use the :only and :except parameters. To pass in multiple controller actions use an array:

before_filter :authorize, :except => [:index, :show]
before_filter :authorize, :only => :delete
July 31, 2008
8 thanks

Multiple filter methods with :only, :except

Notice that this methods accepts *filters param, so you can pass array of methods with :only or :except too

Example

before_filter [:authorize, :set_locale], :except => :login

March 27, 2009
4 thanks

multiple filter example

actually you can have it even shorter with:

before_filter :authorize, :set_locale, :except => :login
October 17, 2009
1 thank

Re: Passing parameters to before_filter

I am not sure I get your “method 1” alec-c4; won’t that define the method each time the before_filter is called? Why not just define the method in the controller?

You can pass parameters or call protected methods with instance_eval:

before_filter :only => :show do |controller|
  controller.instance_eval do
    redirect_to edit_object_path(params[:id])
  end
end
September 29, 2009
1 thank

Passing parameters to before_filter

I’ve found on the net 2 ways to pass parameters to before_filter:

method 1:

before_filter do |c|
c.class.module_eval do
private
def custom_filter
authorize(args)
end
end
end
before_filter :custom_filter

method 2:

before_filter do |c|
c.send(:authorize, args)
end
December 1, 2011 - (>= v3.0.0)
1 thank

This method isn't deprecated

This method was moved to AbstractController::Callbacks, as stated on [1].

It took me a while to figure out ‘what should I use instead before_filter’. Hope this helps anyone that hits the same road I’m in.

1
April 14, 2011
0 thanks

logging before filters

If you need to track and log which before filters are called for the purpose of debugging your app/before_filters. Then here’s a suggestion, how this could be accomplished:

http://stackoverflow.com/questions/4951902/how-to-log-rails-controller-filters-during-rspec-controller-tests/5660475#5660475

February 8, 2015
0 thanks

prepend_before_filter

If you need the method to be called at *the beginning* of the before_filter chain then you should use:

prepend_before_filter

November 22, 2010
0 thanks

another way

because you can pass inline procs as well:

before_filter {authorize(args)}