我的控制器类中包含一些模块。这些模块定义before_filter
:
module BasicFeatures
def filter_method
...
end
def self.included(base)
base.before_filter(:filter_method)
...
end
end
module AdvancedFeatures
include BasicFeatures
...
end
班级:
class BasicController < ApplicationController
include BasicFeatures
end
class AdvancedController < ApplicationController
include AdvancedFeatures
end
BasicFeatures
模块中包含AdvancedFeatures
模块时,其中没有before_filter
个方法。AdvancedController
没有收到before_filter
来电。我需要两个控制器来获取before_filter
而没有任何代码重复。我不知道我是否使用最佳方法,所以我愿意接受任何建议。
答案 0 :(得分:5)
这就是创建ActiveSupport::Concern
的原因。
module BasicFeatures
extend ActiveSupport::Concern
included do
before_filter :require_user
end
def this_is_an_instance_method
'foo'
end
module ClassMethods
def this_is_a_class_method
'bar'
end
end
end
class SomeClass
include BasicFeatures
end
SomeClass.new.this_is_an_instance_method #=> 'foo'
您还可以嵌套它们 - 也就是说,创建包含关注点的问题 - 并且一切都将按预期工作。并here are the docs。
答案 1 :(得分:0)
你可以试试这个。您可以在类包括AdvancedFeatures
的类中包含BasicFeatures模块,而不是在AdvancedFeatures中包含该模块module BasicFeatures
def filter_method
#code....
end
#some others basic methods...
def self.included(base)
base.before_filter(:filter_method)
#some other class method calls
end
end
module AdvancedFeatures
def self.included klass
klass.class_eval do
include BasicFeatures
end
end
#some advanced methods
end