Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Net::HTTP.get show progress

Tags:

ruby

require 'net/http'

File.write(file_name, Net::HTTP.get(URI.parse(url)))

I want to show to the user what's happening here, something like progress because the size of a file can be big. But only the information the user can be interested in, not all the debug information.

Does Net::HTTP.get have such an ability?

like image 225
Incerteza Avatar asked Nov 12 '14 03:11

Incerteza


1 Answers

You can find information on that here: http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Streaming+Response+Bodies

The example snippet used in the docs for just such a thing is:

require 'net/http'

uri = URI("http://apps.sfgov.org/datafiles/view.php?file=sfgis/citylots.zip")

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri

  http.request request do |response|
    file_size = response['content-length'].to_i
    amount_downloaded = 0

    open 'large_file', 'wb' do |io| # 'b' opens the file in binary mode 
      response.read_body do |chunk|
        io.write chunk
        amount_downloaded += chunk.size
        puts "%.2f%" % (amount_downloaded.to_f / file_size * 100)
      end
    end
  end
end
like image 118
Ben Avatar answered Oct 06 '22 20:10

Ben