Passing arguments to filters - best practices
What better ways to pass arguments to filters in Rails controllers?
EDIT: The filter has a different beha开发者_开发知识库vior depending on the parameters passed to it, or depends on the parameters to perform its action. I have an example in my app, where a filter determines how the data is sorted. This filter has a klass param and calls klass.set_filter(param[:order]) to determine :order in the search.
You have to use procs for this.
class FooController < ApplicationController
before_filter { |controller| controller.send(:generic_filter, "XYZ") },
:only => :edit
before_filter { |controller| controller.send(:generic_filter, "ABC") },
:only => :new
private
def generic_filter type
end
end
Edit
One more way to pass the parameter is to override the call
method of ActionController::Filters::BeforeFilter
.
class ActionController::Filters::BeforeFilter
def call(controller, &block)
super controller, *(options[:para] || []), block
if controller.__send__(:performed?)
controller.__send__(:halt_filter_chain, method, :rendered_or_redirected)
end
end
end
Now you can change your before_filter specification as follows
class FooController < ApplicationController
# calls the generic_filter with param1= "foo"
before_filter :generic_filter, :para => "foo", :only => :new
# calls the generic_filter with param1= "foo" and param2="tan"
before_filter :generic_filter, :para => ["foo", "tan"], , :only => :edit
private
def generic_filter para1, para2="bar"
end
end
I -think- you are looking for the use of successive named_scope filters, but I am not sure. We need more information, if that's not what you need.
精彩评论