12

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

1 回答 1

19
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
于 2015-03-12T22:04:28.930 回答