Read from url and write to Tempfile

ruby, temporary-files

Solution

Just do as

open(url) do |url_file|
  tmp_file.write(url_file.read)
end

tmp_file.rewind

tmp_file.read

Look at the documentation example.

The problem in your case was that you were doing a read at the current `IO` pointer in the `temp_file`, that is already at the end when you completed with writes. Thus you need to do a `rewind` before the `read`.

Problem

Say I have this url: Image And I want to write its contents to a tempfile. I am doing it like this: ``` url = http://s3.amazonaws.com/estock/fspid10/27/40/27/6/buddhism-hindu-religion-2740276-o.png tmp_file = Tempfile.new(['chunky_image', '.png']) tmp_file.binmode open(url) do |url_file| tmp_file.write(url_file.read) end ``` But it seems tmp_file is empty. Beacuse when I do: ``` tmp_file.read => # "" ``` What am I missing?

Original source