Skip to content

Commit

Permalink
Actually upload the files when passed as File or Pathname
Browse files Browse the repository at this point in the history
This is a follow-up to rails#45606

We were storing the file metadata in Blob and Attachment but we were not
actually uploading the files (into the file system for instance for disk
storage).

It was failing silently so I made it explicit what is accepted and what
is unexpected
  • Loading branch information
dorianmariecom committed Sep 25, 2023
1 parent f57d54c commit 94a7149
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
18 changes: 17 additions & 1 deletion activestorage/lib/active_storage/attached/changes/create_one.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ def upload
)
when Hash
blob.upload_without_unfurling(attachable.fetch(:io))
when File
blob.upload_without_unfurling(attachable)
when Pathname
blob.upload_without_unfurling(attachable.open)
when ActiveStorage::Blob
when String
else
raise(
ArgumentError,
"Could not upload: expected attachable, " \
"got #{attachable.inspect}"
)
end
end

Expand Down Expand Up @@ -97,7 +109,11 @@ def find_or_build_blob
service_name: attachment_service_name
)
else
raise ArgumentError, "Could not find or build blob: expected attachable, got #{attachable.inspect}"
raise(
ArgumentError,
"Could not find or build blob: expected attachable, " \
"got #{attachable.inspect}"
)
end
end

Expand Down
10 changes: 10 additions & 0 deletions activestorage/test/models/attached/one_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ class ActiveStorage::OneAttachedTest < ActiveSupport::TestCase
assert_not_nil @user.avatar_blob
end

test "uploads the file when passing a File as attachable attribute" do
@user = User.create!(name: "Dorian", avatar: file_fixture("image.gif").open)
assert_nothing_raised { @user.avatar.download }
end

test "creating a record with a Pathname as attachable attribute" do
@user = User.create!(name: "Dorian", avatar: file_fixture("image.gif"))

Expand All @@ -32,6 +37,11 @@ class ActiveStorage::OneAttachedTest < ActiveSupport::TestCase
assert_not_nil @user.avatar_blob
end

test "uploads the file when passing a Pathname as attachable attribute" do
@user = User.create!(name: "Dorian", avatar: file_fixture("image.gif"))
assert_nothing_raised { @user.avatar.download }
end

test "attaching an existing blob to an existing record" do
@user.avatar.attach create_blob(filename: "funky.jpg")
assert_equal "funky.jpg", @user.avatar.filename.to_s
Expand Down

0 comments on commit 94a7149

Please sign in to comment.