我正在尝试使用单独的AuthenticationFilter
类,它将用户角色作为参数,但我无法找到有关如何执行此操作的任何示例。我尝试使用搜索,所有我看到的是调用这样的方法:
before_action -> { some_method :some_value }
或者是自定义类(比如我有)但没有参数:
before_action AuthenticationFilter
这些工作,但我如何调用AuthenticationFilter
并为其指定:superuser
等参数?
请注意:我不想使用单独的课程,这是否可能?
干杯!
答案 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
因此,还注意到使用典型的only
和except
规则时也可以这样做:
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