Skip to content

Instantly share code, notes, and snippets.

@ryanmark
Created December 6, 2018 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmark/c526894c2630944c61c1a86c5a1feb25 to your computer and use it in GitHub Desktop.
Save ryanmark/c526894c2630944c61c1a86c5a1feb25 to your computer and use it in GitHub Desktop.
ruby download with progress
# 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