【问题标题】:order of before_filters in Rails controller and concernsRails 控制器中 before_filters 的顺序和关注点
【发布时间】:2016-01-05 10:19:24
【问题描述】:

我有一个 Rails 问题,定义如下:

module MyConcern
  extend ActiveSupport::Concern

  included do
    before_filter :filter_inside_concern
  end

  def filter_inside_concern
    # ...
  end
end

我在控制器层也有一个before_filter

class MyController < ApplicationController
  before_filter :filter_inside_controller
end

如果我在MyController 中包含MyConcern,调用前置过滤器的顺序是否取决于代码的排列方式?例如,如果我们有

class MyController < ApplicationController
  include MyConcern

  before_filter :filter_inside_controller
end

filter_inside_concern 是否在 filter_inside_controller 之前被调用(反之亦然)?

谢谢!

【问题讨论】:

  • 我认为您可以通过在两个过滤器中添加日志代码来确定自己,您可以看到它的调用顺序。试一试。

标签: ruby-on-rails ruby-on-rails-4 actioncontroller before-filter activesupport-concern


【解决方案1】:

我重新创建了您的情况并发现执行顺序取决于您编写两个过滤器的顺序。

如果你写

  include MyConcern
  before_filter :filter_inside_controller

关注过滤器将首先执行

或者如果你按这个顺序编写过滤器

  before_filter :filter_inside_controller
  include MyConcern

控制器过滤器将首先执行

【讨论】:

  • 这是我直觉上所期望的,但我以前发现过这种事情的奇怪结果,而且总是值得通过日志记录来检查。
  • 我已经通过日志检查并得到了这些结果。当我们包含关注点时,它会在我们编写include 的地方注入included 部分代码。过滤器优先级是从上到下,哪个过滤器在顶部首先执行。
  • 我确定,我的评论确实是针对发帖人的。
【解决方案2】:

如果你使用:

class MyController < ApplicationController
  include MyConcern

  before_filter :filter_inside_controller
end

filter_inside_concern 将在filter_inside_controller 之前被调用

如果您想在filter_inside_concern 之前调用filter_inside_controller,则需要改用prepend_before_filter

class MyController < ApplicationController
  include MyConcern

  prepend_before_filter :filter_inside_controller
end

附带说明,before_filterprepend_before_filter 将被弃用。您应该改用before_actionprepend_before_action

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多