Module: ErpTechSvcs::Extensions::ActiveRecord::IsJson::ClassMethods

Defined in:
lib/erp_tech_svcs/extensions/active_record/is_json.rb

Instance Method Summary collapse

Instance Method Details

#is_json(attr_name) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/erp_tech_svcs/extensions/active_record/is_json.rb', line 16

def is_json(attr_name)
  serialize attr_name, JSON

  extend SingletonMethods
  include InstanceMethods

  # create method to initialize the json field with an empty hash
  define_method("initialize_#{attr_name}_json") do
    if attributes.keys.include?(attr_name.to_s) && send("#{attr_name}").nil?
      send("#{attr_name}=", {})
    end
  end
  after_initialize "initialize_#{attr_name}_json"

  define_method("stringify_keys_for_#{attr_name}_json") do
    if send(attr_name).is_a?(Hash)
      send("#{attr_name}=", send(attr_name).stringify_keys)
    end
  end
  before_save "stringify_keys_for_#{attr_name}_json".to_sym
end