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?