Module: ActiveRecord::Owner::ClassMethods

Defined in:
lib/proto_j/active_record/owner.rb

Instance Method Summary collapse

Instance Method Details

#proto_j(key, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/proto_j/active_record/owner.rb', line 8

def proto_j(key, options={})
  db_column      = options[:db_column] || "#{key}_json"
  settings_class = options[:class] || "#{key.to_s.classify}".constantize

  before_save do |m|
    attributes = {}
    attributes[db_column] = m.send(key).to_json
    m.assign_attributes(attributes, :without_protection => true)
  end

  define_method key do
    var_name = "@#{key}"
    settings = instance_variable_get(var_name)

    unless settings
      settings = settings_class.new(attributes[db_column.to_s])
      instance_variable_set(var_name, settings)
    end

    settings
  end
end