Rails 4关注点:将类实例变量赋予模型

时间:2015-03-11 14:40:56

标签: ruby-on-rails ruby ruby-on-rails-4 activesupport-concern

对于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

1 个答案:

答案 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