Class: DownloadRequest
- Inherits:
-
Object
- Object
- DownloadRequest
- Defined in:
- lib/download_request.rb
Overview
Downloads a file to a specified folder.
Instance Attribute Summary collapse
-
#error ⇒ Object
readonly
Returns the value of attribute error.
-
#file_size ⇒ Object
readonly
Returns the value of attribute file_size.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Class Method Summary collapse
Instance Method Summary collapse
-
#get ⇒ Object
Writes file segments to disk immediately instead of storing in memory.
-
#initialize(url, download_folder) ⇒ DownloadRequest
constructor
A new instance of DownloadRequest.
Constructor Details
#initialize(url, download_folder) ⇒ DownloadRequest
Returns a new instance of DownloadRequest.
17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/download_request.rb', line 17 def initialize(url, download_folder) @url = URI.parse(url) # puts @url.path @http = Net::HTTP.new(@url.host, @url.port) if @url.scheme == "https" @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_NONE end @download_folder = download_folder @file_size = 0 end |
Instance Attribute Details
#error ⇒ Object (readonly)
Returns the value of attribute error.
15 16 17 |
# File 'lib/download_request.rb', line 15 def error @error end |
#file_size ⇒ Object (readonly)
Returns the value of attribute file_size.
15 16 17 |
# File 'lib/download_request.rb', line 15 def file_size @file_size end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
15 16 17 |
# File 'lib/download_request.rb', line 15 def url @url end |
Class Method Details
.get(*args) ⇒ Object
10 11 12 |
# File 'lib/download_request.rb', line 10 def get(*args) new(*args).get end |
Instance Method Details
#get ⇒ Object
Writes file segments to disk immediately instead of storing in memory
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/download_request.rb', line 30 def get return unless @error.nil? dirname = File.dirname(@download_folder) unless File.directory?(dirname) FileUtils.mkdir_p(dirname) end local_file = ::File.open(@download_folder, "wb") partial = true @http.request_get(@url) do |response| case response.code when "200" response.read_body do |segment| local_file.write(segment) end @file_size = ::File.size(@download_folder) partial = false when "302" @error = "Token Not Authorized to Access Specified File" else @error = "#{response.code} #{response.class.name}" end end rescue => e # Net::ReadTimeout, SocketError @error = "(#{e.class}) #{e.}" ensure local_file.close if local_file ::File.delete(@download_folder) if partial && ::File.exist?(@download_folder) end |