Created
November 16, 2017 14:51
-
-
Save lucivaldo/f4f3934cb379dbe9673aab05daff3aed to your computer and use it in GitHub Desktop.
Download file in Ruby with output of the progress
This file contains 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' | |
require 'pry' | |
def fetch(uri_str, limit = 30) | |
# You should choose a better exception. | |
raise ArgumentError, 'too many HTTP redirects' if limit == 0 | |
uri = URI(uri_str) | |
use_ssl = uri.scheme == 'https' ? true : false | |
Net::HTTP.start(uri.host, uri.port, use_ssl: use_ssl) do |http| | |
request = Net::HTTP::Get.new uri | |
http.request request do |response| | |
case response | |
when Net::HTTPSuccess | |
total_bytes = response.content_length | |
total_current = 0 | |
open 'large_file', 'w' do |io| | |
response.read_body do |chunk| | |
io.write chunk | |
total_current += chunk.size | |
progress = total_current.to_f / total_bytes.to_f * 100.0 | |
puts "Progress: %.2f%" % progress | |
end | |
end | |
when Net::HTTPRedirection | |
location = response['location'] | |
warn "redirected to #{location}" | |
fetch(location, limit - 1) | |
else | |
response.value | |
end | |
end | |
end | |
end | |
fetch(ARGV[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment