【问题标题】:Run before filter an large number of actions in Ruby on Rails 4在Ruby on Rails 4中过滤大量动作之前运行
【发布时间】:2016-08-31 11:42:58
【问题描述】:

我的 Rails 应用程序中有很多控制器,我需要在不同控制器中的某些操作之前使用before_filter。 before 过滤器将执行所有这些操作的相同代码。是否有一种干净的 DRY 方式(例如在 application_controller 中)来指定应该运行此 before_filter 的操作列表?我尝试在所有控制器中使用before_filer(9),但这看起来很重复,因为它是相同的代码。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 applicationcontroller


【解决方案1】:

为什么不ApplicationController ?如果您在应用程序控制器中定义任何before_filter,那么它将在每个请求上执行。

现在你说它看起来重复但实际上没有。在 application_controller.rb 中提及 before_filter 实际上代表 DRY AKA,您不必在其他任何地方指定 before_filter

当然,并非所有 9 个控制器都会同时执行,因此ApplicationController 是首选方式

class ApplicationController < ActionController::Base
  ...
  before_filter :pre_execute_action
  ...
end
class MyController < ApplicationController
  ...
  skip_before_filter :pre_execute_action, except: [:methods_for_which_it_should_execute]
  ...
end

试试上面的代码作为参考

【讨论】:

  • 问题是,如果我把它放在 application_controller 中,它将在所有操作之前执行。我希望它只对大约 20% 的动作而不是所有动作执行。我有大约 70 个动作,我希望 before_filter 在 12 个动作之前执行
  • 因此您可以拥有skip_before_filter :method_defined_in_application_controller except: [:methods_for_which_it_should_execute],现在它将仅针对那 20% 的操作运行。您必须在需要执行某些方法的控制器中定义它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
相关资源
最近更新 更多