Class: Datasets::Downloader
- Inherits:
-
Object
- Object
- Datasets::Downloader
- Defined in:
- lib/datasets/downloader.rb
Defined Under Namespace
Classes: ProgressReporter, TooManyRedirects
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.
13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/datasets/downloader.rb', line 13 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
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 |
# File 'lib/datasets/downloader.rb', line 25 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 start_http(@url, headers) do |response| if response.is_a?(Net::HTTPPartialContent) mode = "ab" else start = nil mode = "wb" 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 FileUtils.mv(partial_output_path, output_path) rescue TooManyRedirects => error last_url = error.[/\Atoo many redirections: (.+)\z/, 1] raise TooManyRedirects, "too many redirections: #{@url} .. #{last_url}" end |