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, class_name = nil) ⇒ Object



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

def is_json(attr_name, class_name=nil)
  class_name = if class_name
                 class_name
               else
                 case ::ActiveRecord::Base.connection.instance_values["config"][:adapter]
                   when 'postgresql'
                   ::ActiveRecord::Coders::NestedHstore
                   else
                     JSON
                 end
               end


  serialize attr_name, class_name

  extend SingletonMethods
  include InstanceMethods

  # create method to initialize the json field with an empty hash
  define_method("initialize_#{attr_name}_json") do
    if self.new_record?
      send("#{attr_name}=", {})
    end
  end
  after_initialize "initialize_#{attr_name}_json"
end