shiva shiva - 1 year ago 176
Ruby Question

Ruby how to write to Tempfile

I am trying to create a Tempfile and write some text into it. But I get this strange behaviour in rails console

=> #<File:/tmp/test_temp20130805-28300-1u5g9dv-0>
>> t << "Test data"
=> #<File:/tmp/test_temp20130805-28300-1u5g9dv-0>
>> t.write("test data")
=> 9
?> t.path
=> ""

I also tried
cat /tmp/test_temp20130805-28300-1u5g9dv-0
but the file is empty

Am I missing anything ? Or what's the proper way to write to Tempfile ?

FYI I'm using ruby 1.8.7 and rails 2.3.12

Answer Source

You're going to want to close the temp file after writing to it. Just add a t.close to the end. I bet the file has buffered output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download