Skip to content

Commit 94c90ec

Browse files
authored
Merge pull request rails#45606 from dorianmariefr/build-blob-from-file-or-pathname
Allow attaching File or Pathname to has_one_attached
2 parents 99e2999 + 22bacd7 commit 94c90ec

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

activestorage/CHANGELOG.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
* Allow attaching File and Pathname when assigning attributes, e.g.
2+
3+
```ruby
4+
User.create!(avatar: File.open("image.jpg"))
5+
User.create!(avatar: file_fixture("image.jpg"))
6+
```
7+
8+
*Dorian Marié*
9+
110
## Rails 7.1.0.beta1 (September 13, 2023) ##
211

312
* Disables the session in `ActiveStorage::Blobs::ProxyController`

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,20 @@ def find_or_build_blob
8282
)
8383
when String
8484
ActiveStorage::Blob.find_signed!(attachable, record: record)
85+
when File
86+
ActiveStorage::Blob.build_after_unfurling(
87+
io: attachable,
88+
filename: File.basename(attachable),
89+
record: record,
90+
service_name: attachment_service_name
91+
)
92+
when Pathname
93+
ActiveStorage::Blob.build_after_unfurling(
94+
io: attachable.open,
95+
filename: File.basename(attachable),
96+
record: record,
97+
service_name: attachment_service_name
98+
)
8599
else
86100
raise ArgumentError, "Could not find or build blob: expected attachable, got #{attachable.inspect}"
87101
end

activestorage/test/models/attached/one_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,22 @@ class ActiveStorage::OneAttachedTest < ActiveSupport::TestCase
1616
ActiveStorage::Blob.all.each(&:delete)
1717
end
1818

19+
test "creating a record with a File as attachable attribute" do
20+
@user = User.create!(name: "Dorian", avatar: file_fixture("image.gif").open)
21+
22+
assert_equal "image.gif", @user.avatar.filename.to_s
23+
assert_not_nil @user.avatar_attachment
24+
assert_not_nil @user.avatar_blob
25+
end
26+
27+
test "creating a record with a Pathname as attachable attribute" do
28+
@user = User.create!(name: "Dorian", avatar: file_fixture("image.gif"))
29+
30+
assert_equal "image.gif", @user.avatar.filename.to_s
31+
assert_not_nil @user.avatar_attachment
32+
assert_not_nil @user.avatar_blob
33+
end
34+
1935
test "attaching an existing blob to an existing record" do
2036
@user.avatar.attach create_blob(filename: "funky.jpg")
2137
assert_equal "funky.jpg", @user.avatar.filename.to_s

0 commit comments

Comments
 (0)