From 78afac1116d744caa9f2c2b5630668a2af0fd062 Mon Sep 17 00:00:00 2001 From: Matthew Hinea Date: Tue, 16 Jan 2024 16:45:53 -0800 Subject: [PATCH 1/2] JSON: serialize empty arrays as `nil` --- lib/superstore/types/json_type.rb | 3 +++ test/unit/types/json_type_test.rb | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/superstore/types/json_type.rb b/lib/superstore/types/json_type.rb index bc19ba6d..b7ad7f33 100644 --- a/lib/superstore/types/json_type.rb +++ b/lib/superstore/types/json_type.rb @@ -1,6 +1,9 @@ module Superstore module Types class JsonType < Base + def serialize(value) + value if value.present? + end end end end diff --git a/test/unit/types/json_type_test.rb b/test/unit/types/json_type_test.rb index 93ed4efe..29484aab 100644 --- a/test/unit/types/json_type_test.rb +++ b/test/unit/types/json_type_test.rb @@ -1,4 +1,20 @@ require 'test_helper' class Superstore::Types::JsonTypeTest < Superstore::Types::TestCase + test 'serializes empty array to nil' do + comments = { 'foo' => 'bar' } + issue1 = Issue.new(comments:) + issue2 = Issue.new(comments: []) + issue3 = Issue.new(comments: {}) + + assert_equal comments, issue1.comments + assert_equal [], issue2.comments + assert_equal({}, issue3.comments) + + [issue1, issue2].each(&:save!).each(&:reload) + + assert_equal comments, issue1.comments + assert_nil issue2.comments + assert_equal({}, issue3.comments) + end end From 7c7eb50987fc981b1289269732eb7ac17b8693b4 Mon Sep 17 00:00:00 2001 From: Matthew Hinea Date: Fri, 19 Jan 2024 13:23:06 -0800 Subject: [PATCH 2/2] Fix test --- test/unit/types/json_type_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/unit/types/json_type_test.rb b/test/unit/types/json_type_test.rb index 29484aab..18965600 100644 --- a/test/unit/types/json_type_test.rb +++ b/test/unit/types/json_type_test.rb @@ -1,7 +1,7 @@ require 'test_helper' class Superstore::Types::JsonTypeTest < Superstore::Types::TestCase - test 'serializes empty array to nil' do + test 'serializes empty json to nil' do comments = { 'foo' => 'bar' } issue1 = Issue.new(comments:) issue2 = Issue.new(comments: []) @@ -11,10 +11,10 @@ class Superstore::Types::JsonTypeTest < Superstore::Types::TestCase assert_equal [], issue2.comments assert_equal({}, issue3.comments) - [issue1, issue2].each(&:save!).each(&:reload) + [issue1, issue2, issue3].each(&:save!).each(&:reload) assert_equal comments, issue1.comments assert_nil issue2.comments - assert_equal({}, issue3.comments) + assert_nil issue3.comments end end