Skip to content

Instantly share code, notes, and snippets.

@petems
Last active November 18, 2021 11:05
Show Gist options
  • Save petems/6581418 to your computer and use it in GitHub Desktop.
Save petems/6581418 to your computer and use it in GitHub Desktop.
An example http download with Progress Bar output in the command line with Ruby and the native `net/http` library...
#from http://stackoverflow.com/questions/2301009/get-file-size-before-downloading-counting-how-much-already-downloaded-httpru
require "net/http"
require "uri"
require "progressbar"
url = "http://ipv4.download.thinkbroadband.com/5MB.zip"
url_base = url.split("/")[2]
url_path = "/" + url.split("/")[3..-1].join("/")
@counter = 0
Net::HTTP.start(url_base) do |http|
response = http.request_head((url_path))
ProgressBar
pbar = ProgressBar.new("file name:", response["content-length"].to_i)
File.open("test.file", "w") { |f|
http.get((url_path)) do |str|
f.write str
@counter += str.length
pbar.set(@counter)
end
}
pbar.finish
end
puts "Done."
source "https://rubygems.org"
gem "progressbar"
$ bundle exec ruby download_progress.rb
file name:: 100% |oooooooooooooooooooooooooooooooooooooooooooo| Time: 0:00:00
Done.
@nhanco
Copy link

nhanco commented Dec 3, 2015

it's not work.
Ruby says: undefined method ‘integer?’ for "file name:":String

@joshuapinter
Copy link

Can you fix the formatting of:

  @counter += str.length 
  pbar.set(@counter)

@reymillenium
Copy link

reinier@Reiniers-MacBook-Pro progressbar % bundle exec ruby download_progress.rb
download_progress.rb:14:in block in <main>': undefined method escape' for URI:Module (NoMethodError)
from /Users/reinier/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/net/http.rb:960:in start' from /Users/reinier/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/net/http.rb:621:in start'
from download_progress.rb:13:in `

'
reinier@Reiniers-MacBook-Pro progressbar %

@petems
Copy link
Author

petems commented Nov 18, 2021

This is a super old gist that I've forgotten about, but I'll see if I can get a Ruby 3.0 version working 😄

@petems
Copy link
Author

petems commented Nov 18, 2021

Can you fix the formatting of:

  @counter += str.length 
  pbar.set(@counter)

Done!

@petems
Copy link
Author

petems commented Nov 18, 2021

reinier@Reiniers-MacBook-Pro progressbar % bundle exec ruby download_progress.rb download_progress.rb:14:in block in <main>': undefined method escape' for URI:Module (NoMethodError) from /Users/reinier/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/net/http.rb:960:in start' from /Users/reinier/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/net/http.rb:621:in start' from download_progress.rb:13:in `

'
reinier@Reiniers-MacBook-Pro progressbar %

Fixed, the URI.escape had been deprecated for a while it seems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment