Skip to content

Commit

Permalink
fix ActionText::Attachable#as_json to allow options
Browse files Browse the repository at this point in the history
  • Loading branch information
a5-stable committed Sep 26, 2023
1 parent b5d63b9 commit 7809146
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
18 changes: 13 additions & 5 deletions actiontext/lib/action_text/attachable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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+.
#
Expand Down Expand Up @@ -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
9 changes: 9 additions & 0 deletions actiontext/test/unit/attachable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 7809146

Please sign in to comment.