ruby-on-rails - 将参数传递给过滤器 - 最佳实践

标签 ruby-on-rails argument-passing filter

有什么更好的方法可以将参数传递给 Rails Controller 中的过滤器?

编辑:过滤器具有不同的行为,这取决于传递给它的参数,或者取决于执行其操作的参数。 我的应用程序中有一个示例,其中过滤器确定数据的排序方式。这个过滤器有一个 klass 参数并调用 klass.set_filter(param[:order]) 来确定搜索中的 :order。

最佳答案

你必须为此使用 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

编辑

另一种传递参数的方法是覆盖 ActionController::Filters::BeforeFiltercall 方法。

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

关于ruby-on-rails - 将参数传递给过滤器 - 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2327682/

相关文章:

python - 什么是 Ruby 中的 Python 文档字符串?

mysql - Rails 认为我的连接表有不同的列名

c - 有好的参数检查策略吗?

c++ - 如果大小未知,如何通过引用将一维数组作为参数传递?

ruby-on-rails - FUSE ESB 支持 RabbitMQ 吗?

php - 函数中的可变长度引用参数列表

ruby - 二维数组 - 如何删除重复值但保持子数组分开

arrays - 过滤 coffeescript 中的记录数组以返回年龄 > 50 的所有记录

动态输入值的 jQuery 选择器

ruby-on-rails - 在 rails 迁移期间如何避免 id 字段上的隐式序列