blob: edbd20a6c152971dd3573a6283e8081011301dcc (
plain) (
blame)
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
62
63
64
65
|
module ActiveRecord
module Type
class Serialized < DelegateClass(ActiveModel::Type::Value) # :nodoc:
undef to_yaml if method_defined?(:to_yaml)
include ActiveModel::Type::Helpers::Mutable
attr_reader :subtype, :coder
def initialize(subtype, coder)
@subtype = subtype
@coder = coder
super(subtype)
end
def deserialize(value)
if default_value?(value)
value
else
coder.load(super)
end
end
def serialize(value)
return if value.nil?
unless default_value?(value)
super coder.dump(value)
end
end
def inspect
Kernel.instance_method(:inspect).bind(self).call
end
def changed_in_place?(raw_old_value, value)
return false if value.nil?
raw_new_value = encoded(value)
raw_old_value.nil? != raw_new_value.nil? ||
subtype.changed_in_place?(raw_old_value, raw_new_value)
end
def accessor
ActiveRecord::Store::IndifferentHashAccessor
end
def assert_valid_value(value)
if coder.respond_to?(:assert_valid_value)
coder.assert_valid_value(value, action: "serialize")
end
end
private
def default_value?(value)
value == coder.load(nil)
end
def encoded(value)
unless default_value?(value)
coder.dump(value)
end
end
end
end
end
|