views:

155

answers:

2

What better ways to pass arguments to filters in Rails controllers?

EDIT: The filter has a different behavior 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.

A: 

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.

Trevoke
No, the question isn't about models or scopes for models.
nanda
+2  A: 

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
KandadaBoggu
I know. I just want to know if there are others (and betters, more semantic) ways to do this.
nanda
I have edited the answer to add another scenario. Take a look.
KandadaBoggu
Thanks Kandada, this looks much better =D
nanda