对于Rails问题,我可以通过包含它们来通过模块提供我的模型类方法和实例方法。我没有发现博客条目或帖子提及我如何在我的模型中包含变量。
具体来说,我想给我的包含模型一个类实例变量@question
,但我不知道在模块中放置声明的位置,以便应用它。如果模型本身声明了变量,我还希望覆盖类实例变量。
ActiveSupport::Concern
模块是否真的关心变量?
module ContentAttribute
extend ActiveSupport::Concern
def foo
p "hi"
end
module ClassMethods
# @question = "I am a generic question." [doesn't work]
def bar
p "yo"
end
end
end
class Video < ActiveRecord::Base
include ContentAttribute
# @question = "Specific question"; [should override the generic question]
end
答案 0 :(得分:16)
module ContentAttribute
extend ActiveSupport::Concern
included do
self.question = "I am a generic question."
end
module ClassMethods
attr_accessor :question
end
end
然后,在视频......
class Video < ActiveRecord::Base
include ContentAttribute
self.question = "Specific question"
end