Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to filters - best practices

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.

like image 531
nanda Avatar asked Nov 27 '25 08:11

nanda


1 Answers

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
like image 99
Harish Shetty Avatar answered Nov 30 '25 00:11

Harish Shetty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!