如何仅对某些操作使用 Rails before_action 条件?

Par*_*ker 5 ruby-on-rails before-filter

我有一个具有许多操作的控制器(比如说action1、action2、action3和action4)。我有一个before_action过滤器,我想排除一些操作,接近:

before_action :filter_thing, except: [:action3, :action4]
Run Code Online (Sandbox Code Playgroud)

但是,我希望有条件地调用过滤器action2。

我尝试简单地将其分成两个before_action,但第二个似乎覆盖了第一个;在下面的代码中filter_thing没有被调用action1:

before_action :filter_thing, except: [:action3, :action4]
before_action :filter_thing, only: [:action2], unless: :should_not_filter?
Run Code Online (Sandbox Code Playgroud)

我想也许我可以使用条件skip_before_action:

skip_before_action :filter_thing, only: :action2, if: :should_not_filter?
Run Code Online (Sandbox Code Playgroud)

但它似乎忽略了这个if:论点。

有没有办法有条件地将过滤器仅应用于某些操作?

Par*_*ker 4

这是我想出的解决方法:

before_action :filter_thing,
              except[:action3, :action4],
              unless: -> { params[:action] == "action2" && should_not_filter? }
Run Code Online (Sandbox Code Playgroud)

我仍然不完全满意,因为上面的内容很复杂且难以阅读。