How to check the success of IO.copy_stream

The big answer here explains how to load a file in Ruby without loading it into memory:

stack overflow

require 'open-uri' download = open('http://example.com/image.png') IO.copy_stream(download, '~/image.png') 

How would I make sure that calling IO.copy_stream to download the file was actually successful - meaning that the downloaded file is the same file that I intended to download, and not half the downloaded damaged file? The documentation says that IO.copy_stream returns the number of bytes it copies, but how do I know the number of bytes expected when I haven't uploaded a file yet?

+5
source share
1 answer

OpenURI open returns an object that provides HTTP response headers, so you can get the expected number of bytes from the Content-Length header and compare it with the return value of IO.copy_stream :

 require 'open-uri' download = open 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png' bytes_expected = download.meta['content-length'] bytes_copied = IO.copy_stream download, 'image.png' if bytes_expected != bytes_copied raise "Expected #{bytes_expected} bytes but got #{bytes_copied}" end 

It would be surprising if open run without errors, and this check still failed, but you never know.

+5
source

Source: https://habr.com/ru/post/1244626/


All Articles