aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/downloader.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activestorage/lib/active_storage/downloader.rb')
-rw-r--r--activestorage/lib/active_storage/downloader.rb44
1 files changed, 44 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..87be6efb05
--- /dev/null
+++ b/activestorage/lib/active_storage/downloader.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module ActiveStorage
+ class Downloader #:nodoc:
+ def initialize(blob, tempdir: nil)
+ @blob = blob
+ @tempdir = tempdir
+ end
+
+ def download_blob_to_tempfile
+ open_tempfile do |file|
+ download_blob_to file
+ verify_integrity_of file
+ yield file
+ end
+ end
+
+ private
+ attr_reader :blob, :tempdir
+
+ def open_tempfile
+ file = Tempfile.open([ "ActiveStorage-#{blob.id}-", blob.filename.extension_with_delimiter ], tempdir)
+
+ 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 verify_integrity_of(file)
+ unless Digest::MD5.file(file).base64digest == blob.checksum
+ raise ActiveStorage::IntegrityError
+ end
+ end
+ end
+end