2017-10-22 13:16:59 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-01-22 17:09:13 -05:00
|
|
|
require "tmpdir"
|
2018-05-16 22:12:31 -04:00
|
|
|
require "active_support/core_ext/string/filters"
|
2018-01-22 17:09:13 -05:00
|
|
|
|
2017-10-22 13:16:59 -04:00
|
|
|
module ActiveStorage
|
|
|
|
module Downloading
|
2018-05-16 22:12:31 -04:00
|
|
|
def self.included(klass)
|
|
|
|
ActiveSupport::Deprecation.warn <<~MESSAGE.squish, caller_locations(2)
|
|
|
|
ActiveStorage::Downloading is deprecated and will be removed in Active Storage 6.1.
|
|
|
|
Use ActiveStorage::Blob#open instead.
|
|
|
|
MESSAGE
|
|
|
|
end
|
|
|
|
|
2017-10-22 13:16:59 -04:00
|
|
|
private
|
2017-11-02 15:07:04 -04:00
|
|
|
# Opens a new tempfile in #tempdir and copies blob data into it. Yields the tempfile.
|
2018-01-22 17:09:13 -05:00
|
|
|
def download_blob_to_tempfile #:doc:
|
2018-01-26 19:48:32 -05:00
|
|
|
open_tempfile_for_blob do |file|
|
2017-10-22 13:16:59 -04:00
|
|
|
download_blob_to file
|
|
|
|
yield file
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-01-26 19:48:32 -05:00
|
|
|
def open_tempfile_for_blob
|
|
|
|
tempfile = Tempfile.open([ "ActiveStorage", blob.filename.extension_with_delimiter ], tempdir)
|
|
|
|
|
|
|
|
begin
|
|
|
|
yield tempfile
|
|
|
|
ensure
|
|
|
|
tempfile.close!
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-10-22 23:14:44 -04:00
|
|
|
# Efficiently downloads blob data into the given file.
|
2018-01-22 17:09:13 -05:00
|
|
|
def download_blob_to(file) #:doc:
|
2017-10-22 13:16:59 -04:00
|
|
|
file.binmode
|
|
|
|
blob.download { |chunk| file.write(chunk) }
|
2018-04-23 17:42:47 -04:00
|
|
|
file.flush
|
2017-10-22 13:16:59 -04:00
|
|
|
file.rewind
|
|
|
|
end
|
2017-11-02 15:07:04 -04:00
|
|
|
|
|
|
|
# Returns the directory in which tempfiles should be opened. Defaults to +Dir.tmpdir+.
|
2018-01-22 17:09:13 -05:00
|
|
|
def tempdir #:doc:
|
2017-11-02 15:07:04 -04:00
|
|
|
Dir.tmpdir
|
|
|
|
end
|
2017-10-22 13:16:59 -04:00
|
|
|
end
|
|
|
|
end
|