Skip to content

Commit 81ae40b

Browse files
committed
Fix Rack::Test::UploadedFile.new to work with StringIO
Instantiating Rack::Test::UplaodedFile with StringIO no longer causes an exception.
1 parent 4b183e4 commit 81ae40b

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

activestorage/lib/active_storage/attached/changes/create_one.rb

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,12 @@ def blob
2222

2323
def upload
2424
case attachable
25-
when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
25+
when ActionDispatch::Http::UploadedFile
2626
blob.upload_without_unfurling(attachable.open)
27+
when Rack::Test::UploadedFile
28+
blob.upload_without_unfurling(
29+
attachable.respond_to?(:open) ? attachable.open : attachable
30+
)
2731
when Hash
2832
blob.upload_without_unfurling(attachable.fetch(:io))
2933
end
@@ -53,14 +57,22 @@ def find_or_build_blob
5357
case attachable
5458
when ActiveStorage::Blob
5559
attachable
56-
when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
60+
when ActionDispatch::Http::UploadedFile
5761
ActiveStorage::Blob.build_after_unfurling(
5862
io: attachable.open,
5963
filename: attachable.original_filename,
6064
content_type: attachable.content_type,
6165
record: record,
6266
service_name: attachment_service_name
6367
)
68+
when Rack::Test::UploadedFile
69+
ActiveStorage::Blob.build_after_unfurling(
70+
io: attachable.respond_to?(:open) ? attachable.open : attachable,
71+
filename: attachable.original_filename,
72+
content_type: attachable.content_type,
73+
record: record,
74+
service_name: attachment_service_name
75+
)
6476
when Hash
6577
ActiveStorage::Blob.build_after_unfurling(
6678
**attachable.reverse_merge(

activestorage/test/models/attached/one_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,15 @@ class ActiveStorage::OneAttachedTest < ActiveSupport::TestCase
5656
assert_equal "racecar.jpg", @user.avatar.filename.to_s
5757
end
5858

59+
test "attaching StringIO attachable to an existing record" do
60+
upload = Rack::Test::UploadedFile.new StringIO.new(""), original_filename: "test.txt"
61+
62+
@user.avatar.attach upload
63+
64+
assert_not_nil @user.avatar_attachment
65+
assert_not_nil @user.avatar_blob
66+
end
67+
5968
test "attaching a new blob from an uploaded file to an existing record passes record" do
6069
upload = fixture_file_upload("racecar.jpg")
6170
def upload.open

0 commit comments

Comments
 (0)