Class: Bio::TwoBit::Downloader
- Inherits:
-
Object
- Object
- Bio::TwoBit::Downloader
- Defined in:
- lib/bio/twobit/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.
16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/bio/twobit/downloader.rb', line 16 def initialize(url) url = if url.is_a?(URI::Generic) url.dup else URI.parse(url) end @url = url return if @url.is_a?(URI::HTTP) raise ArgumentError, "download URL must be HTTP or HTTPS: <#{@url}>" end |
Instance Method Details
#download(output_path) ⇒ Object
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 68 69 70 71 72 |
# File 'lib/bio/twobit/downloader.rb', line 28 def download(output_path) return if output_path.exist? output_path.parent.mkpath headers = { "Accept-Encoding" => "identity", "User-Agent" => "BioTwobit/#{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 => e last_url = e.[/\Atoo many redirections: (.+)\z/, 1] raise TooManyRedirects, "too many redirections: #{@url} .. #{last_url}" end |