2

我有一个 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

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

class MyController < ApplicationController
  include MyConcern

  before_filter :filter_inside_controller
end

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

谢谢!

4

2 回答 2

3

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

如果你写

  include MyConcern
  before_filter :filter_inside_controller

关注过滤器将首先执行

或者如果您按此顺序编写过滤器

  before_filter :filter_inside_controller
  include MyConcern

控制器过滤器将首先执行

于 2016-01-05T10:35:38.103 回答
1

如果您使用:

class MyController < ApplicationController
  include MyConcern

  before_filter :filter_inside_controller
end

filter_inside_concern之前会被调用filter_inside_controller

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

class MyController < ApplicationController
  include MyConcern

  prepend_before_filter :filter_inside_controller
end

作为旁注,before_filterprepend_before_filter被弃用。您应该使用before_actionandprepend_before_action来代替。

于 2016-01-30T19:00:26.877 回答