Merge pull request #49272 from a5-stable/attachable-as-json

Fix as_json behavior in ActionText::Attachable
This commit is contained in:
Rafael Mendonça França 2023-09-26 12:13:32 -04:00 committed by GitHub
commit cf44b9e3b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 5 deletions

@ -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

@ -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