aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/downloader.rb
diff options
context:
space:
mode:
authorGeorge Claghorn <george@basecamp.com>2018-05-16 22:12:31 -0400
committerGeorge Claghorn <george@basecamp.com>2018-05-16 22:12:31 -0400
commitee21b7c2eb64def8f00887a9fafbd77b85f464f1 (patch)
treef7aae9cbf8ed6dd0921e9cf22ef14e1da7a3273f /activestorage/lib/active_storage/downloader.rb
parentbfe4248c78ce6e93ebba8c7b9ada1c68cd79bb85 (diff)
downloadrails-ee21b7c2eb64def8f00887a9fafbd77b85f464f1.tar.gz
rails-ee21b7c2eb64def8f00887a9fafbd77b85f464f1.tar.bz2
rails-ee21b7c2eb64def8f00887a9fafbd77b85f464f1.zip
Add ActiveStorage::Blob#open
[David Robertson & George Claghorn]
Diffstat (limited to 'activestorage/lib/active_storage/downloader.rb')
-rw-r--r--activestorage/lib/active_storage/downloader.rb40
1 files changed, 40 insertions, 0 deletions
diff --git a/activestorage/lib/active_storage/downloader.rb b/activestorage/lib/active_storage/downloader.rb
new file mode 100644
index 0000000000..7f5b4936a5
--- /dev/null
+++ b/activestorage/lib/active_storage/downloader.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module ActiveStorage
+ class Downloader
+ def initialize(blob)
+ @blob = blob
+ end
+
+ def download_blob_to_tempfile
+ open_tempfile do |file|
+ download_blob_to file
+ yield file
+ end
+ end
+
+ private
+ attr_reader :blob
+
+ def open_tempfile
+ file = Tempfile.open([ "ActiveStorage", tempfile_extension_with_delimiter ])
+
+ begin
+ yield file
+ ensure
+ file.close!
+ end
+ end
+
+ def download_blob_to(file)
+ file.binmode
+ blob.download { |chunk| file.write(chunk) }
+ file.flush
+ file.rewind
+ end
+
+ def tempfile_extension_with_delimiter
+ blob.filename.extension_with_delimiter
+ end
+ end
+end