1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
# frozen_string_literal: true
module ActiveRecord
module Coders # :nodoc:
class ColumnSerializer # :nodoc:
attr_reader :object_class
attr_reader :coder
def initialize(attr_name, coder, object_class = Object)
@attr_name = attr_name
@object_class = object_class
@coder = coder
check_arity_of_constructor
end
def init_with(coder) # :nodoc:
@attr_name = coder["attr_name"]
@object_class = coder["object_class"]
@coder = coder["coder"]
end
def dump(object)
return if object.nil?
assert_valid_value(object, action: "dump")
coder.dump(object)
end
def load(payload)
if payload.nil?
if @object_class != ::Object
return @object_class.new
end
return nil
end
object = coder.load(payload)
assert_valid_value(object, action: "load")
object ||= object_class.new if object_class != Object
object
end
# Public because it's called by Type::Serialized
def assert_valid_value(object, action:)
unless object.nil? || object_class === object
raise SerializationTypeMismatch,
"can't #{action} `#{@attr_name}`: was supposed to be a #{object_class}, but was a #{object.class}. -- #{object.inspect}"
end
end
private
def check_arity_of_constructor
load(nil)
rescue ArgumentError
raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor."
end
end
end
end
|