对于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
解决方法
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