Skip to content

Instantly share code, notes, and snippets.

@gutenye
Forked from Burgestrand/download-progress.rb
Created December 31, 2011 04:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gutenye/1542920 to your computer and use it in GitHub Desktop.
Save gutenye/1542920 to your computer and use it in GitHub Desktop.
Ruby HTTP file download with progress measurement
require 'net/http'
def download(url)
Thread.new do
thread = Thread.current
thread[:body] = []
thread[:done] = 0
url = URI(url)
Net::HTTP.new(url.host, url.port).get2(url.path) do |res|
length = thread[:length] = res.content_length
res.read_body do |segment|
thread[:body] << segment
thread[:done] += segment.length
thread[:progress] = thread[:done].fdiv(length)
end
end
end
end
thread = download "http://mirror.pnl.gov/releases/10.04/ubuntu-10.04.3-desktop-i386.iso"
puts "%.2f%%" % (thread[:progress]*100) until thread.join(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment