Skip to content

Commit a4730dc

Browse files
committed
Fix serializing of time/date columns using yaml serializer
1 parent 47dbc22 commit a4730dc

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

CHANGELOG.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ recommendations of [keepachangelog.com](http://keepachangelog.com/).
1515

1616
### Fixed
1717

18-
- None
18+
- [#1458](https://github.com/paper-trail-gem/paper_trail/pull/1416) - Fix serializing
19+
of time/date columns using yaml serializer. Previously, these were serialized as ruby
20+
objects which uses a lot of space. Now they are serialized into strings.
1921

2022
## 15.1.0 (2023-10-22)
2123

lib/paper_trail/attribute_serializers/cast_attribute_serializer.rb

+7-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,13 @@ def deserialize(attr, val)
4444
end
4545

4646
def serialize(attr, val)
47-
AttributeSerializerFactory.for(@klass, attr).serialize(val)
47+
serialized = AttributeSerializerFactory.for(@klass, attr).serialize(val)
48+
case serialized
49+
when Date, Time
50+
@klass.connection.type_cast(serialized)
51+
else
52+
serialized
53+
end
4854
end
4955
end
5056
end

spec/paper_trail/attribute_serializers/object_attribute_spec.rb

+26
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,32 @@ module AttributeSerializers
4040
end
4141
end
4242
end
43+
44+
describe "#serialize" do
45+
it "serializes a time object into a plain string" do
46+
time = Time.zone.local(2015, 7, 15, 20, 34, 0)
47+
attrs = { "created_at" => time }
48+
described_class.new(Widget).serialize(attrs)
49+
50+
if ENV["DB"] == "postgres" || ENV["DB"] == "sqlite"
51+
expect(attrs["created_at"]).not_to be_a(ActiveSupport::TimeWithZone)
52+
expect(attrs["created_at"]).to be_a(String)
53+
expect(attrs["created_at"]).to match(/2015/)
54+
else
55+
expect(attrs["created_at"].to_i).to eq(time.to_i)
56+
end
57+
end
58+
end
59+
60+
describe "#deserialize" do
61+
it "deserializes a time object correctly" do
62+
time = 1.day.ago
63+
attrs = { "created_at" => time }
64+
described_class.new(Widget).serialize(attrs)
65+
described_class.new(Widget).deserialize(attrs)
66+
expect(attrs["created_at"].to_i).to eq(time.to_i)
67+
end
68+
end
4369
end
4470
end
4571
end

0 commit comments

Comments
 (0)