Hommer Smith
Hommer Smith

Reputation: 27852

Read from url and write to Tempfile

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?

Upvotes: 6

Views: 5545

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

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.

Upvotes: 10

bjhaid
bjhaid

Reputation: 9752

You need tmp_file.rewind

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

#You need to bring the cursor back to the start of the file with:

tmp_file.rewind

tmp_file.read 

Upvotes: 6

Related Questions