class TTY::File::DownloadFile

Constants

DEFAULT_REDIRECTS

Attributes

dest_path[R]
limit[R]
uri[R]

Public Class Methods

new(url, dest_path, limit: nil) click to toggle source

@options

# File lib/tty/file/download_file.rb, line 17
def initialize(url, dest_path, limit: nil)
  @uri       = URI.parse(url)
  @dest_path = dest_path
  @limit     = limit || DEFAULT_REDIRECTS
end

Public Instance Methods

call() click to toggle source

Download a file

@api public

# File lib/tty/file/download_file.rb, line 26
def call
  download(uri, dest_path, limit)
end

Private Instance Methods

download(uri, path, limit) click to toggle source

@api private

# File lib/tty/file/download_file.rb, line 33
def download(uri, path, limit)
  raise DownloadError, "Redirect limit reached!" if limit.zero?
  content = []

  Net::HTTP.start(uri.host, uri.port,
                  use_ssl: uri.scheme == "https") do |http|
    http.request_get(uri.request_uri) do |response|
      case response
      when Net::HTTPSuccess
        response.read_body do |seg|
          content << seg
        end
      when Net::HTTPRedirection
        download(URI.parse(response["location"]), path, limit - 1)
      else
        response.error!
      end
    end
  end
  content.join
end