Class: Datasets::Downloader
- Inherits:
-
Object
- Object
- Datasets::Downloader
- Defined in:
- lib/datasets/downloader.rb
Defined Under Namespace
Classes: ProgressReporter
Instance Method Summary collapse
- #download(output_path) ⇒ Object
-
#initialize(url) ⇒ Downloader
constructor
A new instance of Downloader.
Constructor Details
#initialize(url) ⇒ Downloader
Returns a new instance of Downloader.
11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/datasets/downloader.rb', line 11 def initialize(url) if url.is_a?(URI::Generic) url = url.dup else url = URI.parse(url) end @url = url unless @url.is_a?(URI::HTTP) raise ArgumentError, "download URL must be HTTP or HTTPS: <#{@url}>" end end |
Instance Method Details
#download(output_path) ⇒ Object
23 24 25 26 27 28 29 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 60 61 62 63 64 65 66 67 |
# File 'lib/datasets/downloader.rb', line 23 def download(output_path) output_path.parent.mkpath headers = {"User-Agent" => "Red Datasets/#{VERSION}"} start = nil partial_output_path = Pathname.new("#{output_path}.partial") if partial_output_path.exist? start = partial_output_path.size headers["Range"] = "bytes=#{start}-" end Net::HTTP.start(@url.hostname, @url.port, :use_ssl => (@url.scheme == "https")) do |http| request = Net::HTTP::Get.new(@url.path, headers) http.request(request) do |response| case response when Net::HTTPPartialContent mode = "ab" when Net::HTTPSuccess start = nil mode = "wb" else break end base_name = @url.path.split("/").last size_current = 0 size_max = response.content_length if start size_current += start size_max += start end progress_reporter = ProgressReporter.new(base_name, size_max) partial_output_path.open(mode) do |output| response.read_body do |chunk| size_current += chunk.bytesize progress_reporter.report(size_current) output.write(chunk) end end end end FileUtils.mv(partial_output_path, output_path) end |