From 94a7149a966905b6dbedacba98103e2fff205b17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dorian=20Mari=C3=A9?= Date: Mon, 25 Sep 2023 19:01:21 +0200 Subject: [PATCH] Actually upload the files when passed as File or Pathname This is a follow-up to https://github.com/rails/rails/pull/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 --- .../attached/changes/create_one.rb | 18 +++++++++++++++++- activestorage/test/models/attached/one_test.rb | 10 ++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/activestorage/lib/active_storage/attached/changes/create_one.rb b/activestorage/lib/active_storage/attached/changes/create_one.rb index 5caed68f6846c..d05098a348fb7 100644 --- a/activestorage/lib/active_storage/attached/changes/create_one.rb +++ b/activestorage/lib/active_storage/attached/changes/create_one.rb @@ -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 @@ -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 diff --git a/activestorage/test/models/attached/one_test.rb b/activestorage/test/models/attached/one_test.rb index 987acf731ad13..3a1be9e295b4d 100644 --- a/activestorage/test/models/attached/one_test.rb +++ b/activestorage/test/models/attached/one_test.rb @@ -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")) @@ -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