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?
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With