在控制器之间共享一些 before_filters

Share some before_filters between controllers

我有两个父控制器,一个用于 API,一个用于普通 html 页面。

class ApplicationController < ActionController::Base
    ...
end

class ApiController < ActionController::Metal
    include AbstractController::Callbacks
    ...
end

我想在两个控制器上共享一些 before_filter。我试过这样的事情:

class ApplicationController < ActionController::Base
    include MyFilters
end

class ApiController < ActionController::Metal
    include MyFilters
end

module MyFilters
    before_filter :filter1
    before_filter :filter2

    def filter1
    end

    def filter2
    end
    ...
end

还有这个:

module MyFilters
    def self.included(klass)
        klass.before_filter :filter1
        klass.before_filter :filter2
    end

    def filter1
    end

    def filter2
    end
    ...
end

但在这两种情况下我都收到:

undefined method `before_filter' for MyFilters:Module

实现这个的正确方法是什么?

您可以为此使用 concern

# app/controllers/concerns/my_filters.rb
module MyFilters
  extend ActiveSupport::Concern

  included do
    before_filter :filter1
    before_filter :filter2
  end

  def filter1
  end

  def filter1
  end
end

通过控制器中的标准 include 使用它们:

class ApplicationController < ActionController::Base
  include MyFilters
end

class ApiController < ActionController::Metal
  include MyFilters
end