Class: Paquet::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/paquet/utils.rb

Constant Summary collapse

HTTPS_SCHEME =
"https"
REDIRECTION_LIMIT =
5

Class Method Summary collapse

Class Method Details

.download_file(source, destination, counter = REDIRECTION_LIMIT) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/paquet/utils.rb', line 10

def self.download_file(source, destination, counter = REDIRECTION_LIMIT)
  raise "Too many redirection" if counter == 0

  begin
    f = File.open(destination, "wb")

    uri = URI.parse(source)

    http = Net::HTTP.new(uri.host, uri.port, )
    http.use_ssl = uri.scheme ==  HTTPS_SCHEME

    response = http.get(uri.path)

    case response
    when Net::HTTPSuccess
      f.write(response.body)
    when Net::HTTPRedirection
      counter -= 1
      download_file(response['location'], destination, counter)
    else
      raise "Response not handled: #{response.class}, path: #{uri.path}"
    end
    f.path
  rescue => e
    FileUtils.rm_rf(f.path) rescue nil
    raise e
  ensure
    f.close
  end
end