Skip to content

Commit d79da7b

Browse files
authored
Merge pull request rails#51299 from ElvinEfendi/support-custom-blob-key-in-compose
Support custom blob key in ActiveStorage::Blob#compose similar to other Blob APIs
2 parents 4c2c8f8 + 64178f9 commit d79da7b

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

activestorage/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add support for custom `key` in `ActiveStorage::Blob#compose`.
2+
3+
*Elvin Efendiev*
4+
15
* Add `image/webp` to `config.active_storage.web_image_content_types` when `load_defaults "7.2"`
26
is set.
37

activestorage/app/models/active_storage/blob.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,12 +142,12 @@ def scope_for_strict_loading # :nodoc:
142142
end
143143

144144
# Concatenate multiple blobs into a single "composed" blob.
145-
def compose(blobs, filename:, content_type: nil, metadata: nil)
145+
def compose(blobs, key: nil, filename:, content_type: nil, metadata: nil)
146146
raise ActiveRecord::RecordNotSaved, "All blobs must be persisted." if blobs.any?(&:new_record?)
147147

148148
content_type ||= blobs.pluck(:content_type).compact.first
149149

150-
new(filename: filename, content_type: content_type, metadata: metadata, byte_size: blobs.sum(&:byte_size)).tap do |combined_blob|
150+
new(key: key, filename: filename, content_type: content_type, metadata: metadata, byte_size: blobs.sum(&:byte_size)).tap do |combined_blob|
151151
combined_blob.compose(blobs.pluck(:key))
152152
combined_blob.save!
153153
end

activestorage/test/models/blob_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,14 @@ class ActiveStorage::BlobTest < ActiveSupport::TestCase
135135
assert_equal "All blobs must be persisted.", error.message
136136
end
137137

138+
test "compose with custom key" do
139+
blobs = 3.times.map { create_blob(data: "123", filename: "numbers.txt", content_type: "text/plain", identify: false) }
140+
blob = ActiveStorage::Blob.compose(blobs, key: "custom_key", filename: "all_numbers.txt")
141+
142+
assert_equal "custom_key", blob.key
143+
assert_equal "123123123", blob.download
144+
end
145+
138146
test "image?" do
139147
blob = create_file_blob filename: "racecar.jpg"
140148
assert_predicate blob, :image?

0 commit comments

Comments
 (0)