Passing a parameter to a before filter

Creating a controller filter that accepts a parameter is less than obvious as I found today while trying to add more than basic authentication to a controller.

Turns out that you need to do it like this :

before_filter :only => [:create, :update, :destroy] do |controller|
controller.filter_function(parameter)
end

rather than allowing a parameters array to pass into the before_filter function which would be nice.

2 thoughts on “Passing a parameter to a before filter

  1. Cassiano D'Andrea

    Hi. After reading your post I came out with:

    class ApplicationController  :create
    
      #################################################
      # Sample usage passing a hash as a parameter value.
      parameterized_before_filter :my_filter, 'param1', 'param2', 
                                                { :param3 => :value3 }, :only => :create
    
      #################################################
      # The filter itself.
      def my_filter(*args)
        puts args.inspect
      end
    end
    

    How do you like it? Why doesn’t Rails provide such method out of the box?

    One might also add :parameterized_before_filter directly to ActionController::Base, or even replace the original :before_filter (using :alias_method_chain).

    Thanks for sharing the tip.

    Reply
  2. andrew Post author

    Hi Cassiano,
    I fixed your comment 🙂 WordPress was obviously screwing up your previous attempts.
    The parameterized_before_filter is great much more thought out than my simple attempt.
    I’m not sure why rails doesn’t provide such a method already as it is pretty useful, i guess though that ruby lets you do it pretty easily anyway if in a non newbie friendly way. If you find out the reason please let me know.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *