Q:

Ruby - Save file parts before download finishes

I was looking at downloading scripts in Ruby and most of them end up like this :
File.open(fileName, 'wb') do |output|
  open(@url) do |data|
    output.write(data.read)
  end
end

this approach seems to open a stream and download the file completely and FINALLY save the data to the file...
Is there a way to make the code save the ALREADY DOWNLOADED data to the file periodically ?
for example out of a 100MB Youtube video, I want the script to save every 1MB it downloads to the file and continue doing this until the download is finished...
This way you could open the file with a suitable player and play it before the download is finished.
Thanks...

A:

OpenURI seems to read the entire file before passing it to the block, but you can use Net::HTTP to stream the response body:
require 'net/http'

uri = URI(@url)

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

  http.request request do |response|
    open file_name, 'w' do |io|
      io.sync = true
      response.read_body do |chunk|
        io.write chunk
      end
    end
  end
end

Note the IO#sync= call to set the “sync mode”.

