Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 concerns: Give class instance variables to model

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
like image 637
ZeroMax Avatar asked Mar 11 '15 14:03

ZeroMax


People also ask

What are model concerns in Rails?

A Rails Concern is a module that extends the ActiveSupport::Concern module. Concerns allow us to include modules with methods (both instance and class) and constants into a class so that the including class can use them. The code inside the included block is evaluated in the context of the including class.

What is the reason for using concerns in Rails?

People use Rails concern for mainly for two things: First, to reduce the size of a model that could be separated into several models, and therefore reducing the size. Second, to avoid declaring the same class over and over again.

Can Ruby modules have instance variables?

It is well known that Ruby has instance and class variables, just like any Object-Oriented language. They are both widely used, and you can recognize them by the @a and @@a notation respectively.

Can classes include instance variables?

Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.


1 Answers

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
like image 85
Mark Swardstrom Avatar answered Sep 28 '22 04:09

Mark Swardstrom