Created
January 28, 2019 23:38
-
-
Save blairanderson/94b7e76a9c56d2c25f5c989eac7f81bd to your computer and use it in GitHub Desktop.
ActiveStorage Downloader takes attachment input and yields a tempfile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ActiveStorage::Downloader.new(attachment).download_blob_to_tempfile do |tempfile| | |
do_stuff_with_file(tempfile) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment