-
-
Save gutenye/1542920 to your computer and use it in GitHub Desktop.
Ruby HTTP file download with progress measurement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment