Skip to content

Instantly share code, notes, and snippets.

@apfeltee
Forked from Burgestrand/download-progress.rb
Created January 20, 2016 16:38
Show Gist options
  • Save apfeltee/eb3335778233c7a85eba to your computer and use it in GitHub Desktop.
Save apfeltee/eb3335778233c7a85eba to your computer and use it in GitHub Desktop.
Ruby HTTP file download with progress measurement
require 'net/http'
require 'uri'
def download(url)
Thread.new do
thread = Thread.current
body = thread[:body] = []
url = URI.parse url
Net::HTTP.new(url.host, url.port).request_get(url.path) do |response|
length = thread[:length] = response['Content-Length'].to_i
response.read_body do |fragment|
body << fragment
thread[:done] = (thread[:done] || 0) + fragment.length
thread[:progress] = thread[:done].quo(length) * 100
end
end
end
end
thread = download 'http://caesar.acc.umu.se/mirror/ubuntu-releases/10.04/ubuntu-10.04-desktop-i386.iso'
puts "%.2f%%" % thread[:progress].to_f until thread.join 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment