Rails:如何将参数传递给自定义的before_action类?

时间:2015-07-30 07:17:32

标签: ruby-on-rails ruby-on-rails-4 before-filter

我正在尝试使用单独的AuthenticationFilter类,它将用户角色作为参数,但我无法找到有关如何执行此操作的任何示例。我尝试使用搜索,所有我看到的是调用这样的方法:

before_action -> { some_method :some_value }

或者是自定义类(比如我有)但没有参数:

before_action AuthenticationFilter

这些工作,但我如何调用AuthenticationFilter并为其指定:superuser等参数?

请注意:我不想使用单独的课程,这是否可能?

干杯!

2 个答案:

答案 0 :(得分:2)

哦,我设法解决了。

我注意到rails文档提到*_action来调用与*指定同名的方法。因此,before_action在给定的类中寻找名为before的方法。

因此,我决定制作一个块,并在行动之前直接调用AuthenticationFilter给它参数:

before_action { |c| AuthenticationFilter.before(c, :superuser) }

然后我将AuthenticationFilter类修改为:

class AuthenticationFilter
  class << self
    def before(controller, role)
      puts "Called AuthenticationFilter with role: #{role}"
    end
  end
end

因此,还注意到使用典型的onlyexcept规则时也可以这样做:

before_action only: [:show, :edit] do |c| 
  AuthenticationFilter.before(c, :superuser) 
end

答案 1 :(得分:0)

如何在方法中包装类初始化?

before_action :set_authentication_filter

def set_authentication_filter
  # initialize your class here with custom parameters
end