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.

Tags: , ,

2 Responses to “Passing a parameter to a before filter”

  1. Cassiano D'Andrea Says:

    Hi. After reading your post I came out with:

    class ApplicationController < ActionController::Base
      #################################################
      def self.parameterized_before_filter(filter_name, *args)
        options = args.extract_options!
    
        self.before_filter(options) { |controller| controller.send(filter_name, *args) }
      end
    
      #################################################
      # Sample usage with 2 parameters.
      parameterized_before_filter :my_filter, 'param1', 'param2', :only => :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.

  2. andrew Says:

    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.

Leave a Reply