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.
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',
nly => :create
#################################################
# Sample usage passing a hash as a parameter value.
parameterized_before_filter :my_filter, 'param1', 'param2',
{ :param3 => :value3 },
nly => :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.
Hi Cassiano,
WordPress was obviously screwing up your previous attempts.
I fixed your comment
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.