bymannan
bymannan

Reputation: 1383

rails: how to pass data from class variables to instance variable

Let's say I have this concern.

module Fields
  extend ActiveSupport::Concern

  module ClassMethods
    def add_field(name)
       define_method(name) do
          self.data[name]
        end      
    end
  end
end

And to use it I will do this:

class Content < ActiveRecord::Base
   include Fields
   add_field :title
   add_field :body
end

So far so good. Now I want to populate a default data to the new created field. I would need to do this:

module Fields
  extend ActiveSupport::Concern

  included do
    after_initialize :default_data 
    class_attribute :fields
  end

  def default_data
    self.fields.each do |field|
       self.data[field.to_sym] = "hello"
    end
  end

  module ClassMethods
    def add_field(name)
       define_method(name) do
          self.data[name]
        end
       fields ||= [] 
       fields << name     
    end
  end
end

However, this does not work. self.fields is nil. It seems that I can not pass data from class methods attributes to the instance method.

What I would like to do it define a constant variable or data during the definition of add_field and use that data on the instance.

Any ideas?

Upvotes: 2

Views: 343

Answers (1)

Yan Foto
Yan Foto

Reputation: 11398

If you want to use class attributes with instance accessors you can just use Active Support's class_attribute.

An example from the Rails guide:

class A
  class_attribute :x
end

class B < A; end

class C < B; end

A.x = :a
B.x # => :a
C.x # => :a

B.x = :b
A.x # => :a
C.x # => :b

C.x = :c
A.x # => :a
B.x # => :b

A.x = 1

a1 = A.new
a2 = A.new
a2.x = 2

a1.x # => 1, comes from A
a2.x # => 2, overridden in a2

Upvotes: 1

Related Questions