2

Railsコントローラーのフィルターに引数を渡すより良い方法は?

EDIT:フィルターは、渡されたパラメーターに応じて異なる動作をするか、アクションを実行するパラメーターに依存します。私のアプリには、フィルターがデータの並べ替え方法を決定する例があります。このフィルターには klass パラメータがあり、 klass.set_filter(param[:order]) を呼び出して検索の :order を決定します。

4

2 に答える 2

3

これにはprocsを使用する必要があります。

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

編集

パラメータを渡すもう 1 つの方法は、 のcallメソッドをオーバーライドすることです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

before_filter の仕様を次のように変更できるようになりました

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
于 2010-02-24T19:04:56.017 に答える
0

連続する named_scope フィルターの使用を探していると思いますが、よくわかりません。それが必要でない場合は、さらに情報が必要です。

于 2010-02-24T16:49:20.793 に答える