Skip to content

Commit 6c2132b

Browse files
Fix ActionText::Attachable#as_json
Before this commit, using ActionText and calling `#as_json` on a non-persisted `ActiveStorage::Blob` raised an error. This is because `ActionText::Attachable` is included in `ActiveStorage::Blob` and overrides the `#as_json` method to expose a global signed id. However, a global signed id can only be generated on a persisted instance. This commit fixes the issue by making sure the blob is persisted before exposing the global signed id.
1 parent 4b560ab commit 6c2132b

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

actiontext/lib/action_text/attachable.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def previewable_attachable?
6464
end
6565

6666
def as_json(*)
67-
super.merge(attachable_sgid: attachable_sgid)
67+
super.merge("attachable_sgid" => persisted? ? attachable_sgid : nil)
6868
end
6969

7070
def to_trix_content_attachment_partial_path
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
class ActionText::AttachableTest < ActiveSupport::TestCase
6+
test "as_json is a hash when the attachable is persisted" do
7+
freeze_time do
8+
attachable = ActiveStorage::Blob.create_after_unfurling!(io: StringIO.new("test"), filename: "test.txt", key: 123)
9+
attributes = {
10+
id: attachable.id,
11+
key: "123",
12+
filename: "test.txt",
13+
content_type: "text/plain",
14+
metadata: { identified: true },
15+
service_name: "test",
16+
byte_size: 4,
17+
checksum: "CY9rzUYh03PK3k6DJie09g==",
18+
created_at: Time.zone.now.as_json,
19+
attachable_sgid: attachable.attachable_sgid
20+
}.deep_stringify_keys
21+
22+
assert_equal attributes, attachable.as_json
23+
end
24+
end
25+
26+
test "as_json is a hash when the attachable is a new record" do
27+
attachable = ActiveStorage::Blob.build_after_unfurling(io: StringIO.new("test"), filename: "test.txt", key: 123)
28+
attributes = {
29+
id: nil,
30+
key: "123",
31+
filename: "test.txt",
32+
content_type: "text/plain",
33+
metadata: { identified: true },
34+
service_name: "test",
35+
byte_size: 4,
36+
checksum: "CY9rzUYh03PK3k6DJie09g==",
37+
created_at: nil,
38+
attachable_sgid: nil
39+
}.deep_stringify_keys
40+
41+
assert_equal attributes, attachable.as_json
42+
end
43+
end

0 commit comments

Comments
 (0)