Files
dunlop-core/app/services/json_column_coder.rb
T
2018-01-20 13:02:44 -03:00

35 lines
827 B
Ruby

require 'json'
class JSONColumnCoder
attr_accessor :object_class
def initialize(object_class = Object)
@object_class = object_class
end
def dump(obj)
return if obj.nil?
unless obj.is_a?(object_class)
raise ActiveRecord::SerializationTypeMismatch,
"Attribute was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}"
end
JSON.dump obj
end
def load(json)
return object_class.new if object_class != Object && json.nil?
return json unless json.is_a?(String)
obj = JSON.load(json)
unless obj.is_a?(object_class) || obj.nil?
raise ActiveRecord::SerializationTypeMismatch,
"Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
end
obj ||= object_class.new if object_class != Object
obj
end
end