From d59f80c5ac941c410e369838658c8ef417932105 Mon Sep 17 00:00:00 2001 From: George Claghorn Date: Mon, 31 Oct 2022 17:26:36 -0400 Subject: [PATCH] JSON-encode GlobalIDs as strings --- lib/global_id/global_id.rb | 4 ++++ test/cases/global_id_test.rb | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/lib/global_id/global_id.rb b/lib/global_id/global_id.rb index 71bd802..f6fb736 100644 --- a/lib/global_id/global_id.rb +++ b/lib/global_id/global_id.rb @@ -66,4 +66,8 @@ def hash def to_param Base64.urlsafe_encode64(to_s, padding: false) end + + def as_json(*) + to_s + end end diff --git a/test/cases/global_id_test.rb b/test/cases/global_id_test.rb index 7f77304..f67b1d4 100644 --- a/test/cases/global_id_test.rb +++ b/test/cases/global_id_test.rb @@ -158,6 +158,20 @@ class GlobalIDCreationTest < ActiveSupport::TestCase assert_equal URI('gid://bcx/PersonModel/1'), @person_model_gid.uri end + test 'as JSON' do + assert_equal 'gid://bcx/Person/5', @person_gid.as_json + assert_equal '"gid://bcx/Person/5"', @person_gid.to_json + + assert_equal "gid://bcx/Person/#{@uuid}", @person_uuid_gid.as_json + assert_equal "\"gid://bcx/Person/#{@uuid}\"", @person_uuid_gid.to_json + + assert_equal 'gid://bcx/Person::Child/4', @person_namespaced_gid.as_json + assert_equal '"gid://bcx/Person::Child/4"', @person_namespaced_gid.to_json + + assert_equal 'gid://bcx/PersonModel/1', @person_model_gid.as_json + assert_equal '"gid://bcx/PersonModel/1"', @person_model_gid.to_json + end + test 'model id' do assert_equal '5', @person_gid.model_id assert_equal @uuid, @person_uuid_gid.model_id