在控制器之间共享一些before_filters

时间:2015-02-19 13:12:01

标签: ruby-on-rails ruby ruby-on-rails-3 multiple-inheritance

我有两个父控制器,一个用于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

实现此目的的正确方法是什么?

1 个答案:

答案 0 :(得分:6)

您可以使用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