Sha256: 53a4e52f96734fd03380178149e854869261f6f7604b9148837a15aa79b30ad1

Contents?: true

Size: 1.13 KB

Versions: 4

Compression:

Stored size: 1.13 KB

Contents

module Hem
  module Helper
    def http_download url, target_file, opts = {}
      require 'net/http'
      require 'openssl'
      require 'uri'
      opts = { :progress => Hem.method(:progress) }.merge(opts)
      uri = URI.parse(url)
      size = 0
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = uri.scheme == 'https'

      # TODO: May want to verify SSL validity...
      # http://notetoself.vrensk.com/2008/09/verified-https-in-ruby/#comment-22252
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE

      http.start do
        begin
          file = open(target_file, 'wb+')
          http.request_get(uri.path) do |response|
            size = response.content_length
            response.read_body do |chunk|
              file.write(chunk)
              opts[:progress].call(
                target_file,
                chunk.length,
                size,
                :update
              ) if opts[:progress]
            end
          end
        ensure
          opts[:progress].call(target_file, 0, size, :finsh) if opts[:progress]
          file.close
        end
      end
    end
  end
end

self.extend Hem::Helper

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
hem-1.2.4 lib/hem/helper/http_download.rb
hem-1.2.3 lib/hem/helper/http_download.rb
hem-1.2.2 lib/hem/helper/http_download.rb
hem-1.2.1 lib/hem/helper/http_download.rb