Rails 4 concerns: Give class instance variables to model

ZeroMax picture ZeroMax · Mar 11, 2015 · Viewed 8.5k times · Source

With Rails concerns I can give my model class methods and instance methods through modules by including them. No blog entry or thread that I've found mentions how I can include variables in my model though.

Specifically I would like to give my including model a class instance variable @question, but I don't know where to put the declaration in the module so it is applied. I would also like the class instance variable to be overridden if the model itself declares that variable.

Does the ActiveSupport::Concern module actually care about variables at all?

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

Answer

Mark Swardstrom picture Mark Swardstrom · Mar 12, 2015
module ContentAttribute
  extend ActiveSupport::Concern

  included do
    self.question = "I am a generic question."
  end

  module ClassMethods
    attr_accessor :question
  end

end

Then, in video...

class Video < ActiveRecord::Base
  include ContentAttribute
  self.question = "Specific question"
end