module ErpTechSvcs::Extensions::ActiveRecord::IsJson::ClassMethods

Public Instance Methods

is_json(attr_name) click to toggle source
# 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