Skip to content
This repository was archived by the owner on Nov 9, 2017. It is now read-only.

Commit f66a690

Browse files
Expose chunked downloads
1 parent 9cf3347 commit f66a690

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

lib/active_storage/blob.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ def upload(io)
5656
service.upload(key, io, checksum: checksum)
5757
end
5858

59-
def download
60-
service.download key
59+
def download(&block)
60+
service.download key, &block
6161
end
6262

6363

lib/active_storage/service/disk_service.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ def upload(key, io, checksum: nil)
2020
def download(key)
2121
if block_given?
2222
instrument :streaming_download, key do
23-
File.open(path_for(key)) do |file|
24-
while data = file.binread(64.kilobytes)
23+
File.open(path_for(key), 'rb') do |file|
24+
while data = file.read(64.kilobytes)
2525
yield data
2626
end
2727
end
@@ -55,15 +55,15 @@ def url(key, expires_in:, disposition:, filename:)
5555
instrument :url, key do |payload|
5656
verified_key_with_expiration = ActiveStorage::VerifiedKeyWithExpiration.encode(key, expires_in: expires_in)
5757

58-
generated_url =
58+
generated_url =
5959
if defined?(Rails) && defined?(Rails.application)
6060
Rails.application.routes.url_helpers.rails_disk_blob_path(verified_key_with_expiration, disposition: disposition, filename: filename)
6161
else
6262
"/rails/active_storage/disk/#{verified_key_with_expiration}/#{filename}?disposition=#{disposition}"
6363
end
6464

6565
payload[:url] = generated_url
66-
66+
6767
generated_url
6868
end
6969
end

test/blob_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,19 @@ class ActiveStorage::BlobTest < ActiveSupport::TestCase
1212
assert_equal Digest::MD5.base64digest(data), blob.checksum
1313
end
1414

15+
test "download yields chunks" do
16+
blob = create_blob data: 'a' * 75.kilobytes
17+
chunks = []
18+
19+
blob.download do |chunk|
20+
chunks << chunk
21+
end
22+
23+
assert_equal 2, chunks.size
24+
assert_equal 'a' * 64.kilobytes, chunks.first
25+
assert_equal 'a' * 11.kilobytes, chunks.second
26+
end
27+
1528
test "urls expiring in 5 minutes" do
1629
blob = create_blob
1730

0 commit comments

Comments
 (0)