我有两个父控制器,一个用于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
实现此目的的正确方法是什么?
答案 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