Sha256: a4c33cc7c9af68245bcb8d58bad9c058f7972a1472ac51857f8540444a548783

Contents?: true

Size: 953 Bytes

Versions: 1

Compression:

Stored size: 953 Bytes

Contents

# encoding: utf-8
require "fileutils"
require "uri"

module Paquet
  class Utils
    HTTPS_SCHEME = "https"
    REDIRECTION_LIMIT = 5

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

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

        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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
paquet-0.2.0 ./lib/paquet/utils.rb