From 7809146a03a9523ce7ae9223eb466913161bdddb Mon Sep 17 00:00:00 2001 From: a5-stable Date: Thu, 14 Sep 2023 22:51:20 +0900 Subject: [PATCH] fix ActionText::Attachable#as_json to allow options --- actiontext/lib/action_text/attachable.rb | 18 +++++++++++++----- actiontext/test/unit/attachable_test.rb | 9 +++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/actiontext/lib/action_text/attachable.rb b/actiontext/lib/action_text/attachable.rb index f5214ac85a..d02c571e08 100644 --- a/actiontext/lib/action_text/attachable.rb +++ b/actiontext/lib/action_text/attachable.rb @@ -98,11 +98,6 @@ def previewable_attachable? false end - # Returns the attachable as JSON with the +attachable_sgid+ included. - def as_json(*) - super.merge("attachable_sgid" => persisted? ? attachable_sgid : nil) - end - # Returns the path to the partial that is used for rendering the attachable # in Trix. Defaults to +to_partial_path+. # @@ -142,5 +137,18 @@ def to_rich_text_attributes(attributes = {}) attrs[:height] = attachable_metadata[:height] end.compact end + + private + def attribute_names_for_serialization + super + ["attachable_sgid"] + end + + def read_attribute_for_serialization(key) + if key == "attachable_sgid" + persisted? ? super : nil + else + super + end + end end end diff --git a/actiontext/test/unit/attachable_test.rb b/actiontext/test/unit/attachable_test.rb index d668febfcf..bdf46b42d6 100644 --- a/actiontext/test/unit/attachable_test.rb +++ b/actiontext/test/unit/attachable_test.rb @@ -40,4 +40,13 @@ class ActionText::AttachableTest < ActiveSupport::TestCase assert_equal attributes, attachable.as_json end + + test "attachable_sgid is included in as_json when only option is nil or includes attachable_sgid" do + attachable = ActiveStorage::Blob.create_after_unfurling!(io: StringIO.new("test"), filename: "test.txt", key: 123) + + assert_equal({ "id" => attachable.id }, attachable.as_json(only: :id)) + assert_equal({ "id" => attachable.id }, attachable.as_json(only: [:id])) + assert_equal(attachable.as_json.except("attachable_sgid"), attachable.as_json(except: :attachable_sgid)) + assert_equal(attachable.as_json.except("attachable_sgid"), attachable.as_json(except: [:attachable_sgid])) + end end