Created
December 6, 2018 20:12
-
-
Save ryanmark/c526894c2630944c61c1a86c5a1feb25 to your computer and use it in GitHub Desktop.
ruby download with progress
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
# WIP | |
def download(src, dest) | |
uri = URI.parse(src) | |
yield "Download #{src} to #{dest}" | |
mutex = Mutex.new | |
size = 0 | |
downloaded = 0 | |
Thread.new do | |
File.open(dest, 'w') do |dest_file| | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = (uri.scheme == 'https') | |
http.start do | |
http.request_get(uri.request_uri) do |resp| | |
size = resp['Content-Length'].to_i.freeze | |
resp.read_body do |chunk| | |
dest_file.write chunk | |
downloaded += chunk.size | |
end | |
end | |
end | |
end | |
end | |
loop do | |
if size.positive? | |
pct = ((downloaded / size) * 100.0).round | |
yield "#{pct}%\t#{downloaded} of #{size}" | |
break if downloaded >= size | |
end | |
sleep 0.2 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment