How do I use :progress_proc from OpenURI::OpenRead?

The below is the code I’d like a progress bar for once it is ran on the
command line:

open(File.join(CWD, name), ‘wb’) do |f|
f << open(url).read
end

I found OpenURI::OpenRead :progress_proc and it seems like it’s exactly
what I want. I’m not too sure how to implement it though. Also, does it
use ruby-progressbar? Is this what they mean by Ruby/ProgressBar:

For example, it can be implemented as follows using Ruby/ProgressBar.

So, all I want from it is some kind of text-based progress bar while the
file is being downloaded. Is :progress_proc the thing I need to use to
do that?

Thanks.

Am Mon, 13 May 2013 01:28:32 +0900
schrieb “Rafal C.” [email protected]:

I found OpenURI::OpenRead :progress_proc and it seems like it’s
exactly what I want. I’m not too sure how to implement it though.
Also, does it use ruby-progressbar?

It doesn’t, ruby-progressbar is just a usage example. You are free to
do whatever you want in the :progress_proc and :content_length_proc
callbacks.

So, all I want from it is some kind of text-based progress bar while
the file is being downloaded. Is :progress_proc the thing I need to
use to do that?

The documentation sadly misses a complete working example to
demonstrate the usage, so I’ll just post one here. The following code
downloads the the Ruby 2.0 sourcecode archive in a hopefully clean
matter (apart from the fact that the API of open-uri’s #open method
looks confusing once you use the callback parameters):

# -*- coding: utf-8 -*-
require "open-uri"

TARGET = "http://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p0.tar.bz2"

bytes_total = nil

open(TARGET, "rb",
     :content_length_proc => lambda{|content_length|
       bytes_total = content_length},
     :progress_proc => lambda{|bytes_transferred|
       if bytes_total
         # Print progress
         print("\r#{bytes_transferred}/#{bytes_total}")
       else
         # We don’t know how much we get, so just print number
         # of transferred bytes
         print("\r#{bytes_transferred} (total size unknown)")
       end
     }) do |page|
  # Now the real operation
  File.open("ruby-2.0.0.tar-bz2", "wb") do |file|
    # The file may not fit into RAM entirely, so copy it
    # chunk by chunk.
    while chunk = page.read(1024)
      file.write(chunk)
    end
  end
end

The above example just prints out the number of already transferred
bytes together with the number of total bytes, but you can of course
convert the numbers to MiB, GiB, etc., calculate a percentage
value or display a progress bar. \r is your friend to overwrite the
current line on the standard output (but remember to terminate with \n
once you’re done).

Thanks.

Vale,
Marvin.


Blog: http://pegasus-alpha.eu/blog

ASCII-Ribbon-Kampagne () | ASCII Ribbon Campaign ()