Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

t = Tempfile.new("test_temp") # => #<File:/tmp/test_temp20130805-28300-1u5g9dv-0> t << "Test data"              # => #<File:/tmp/test_temp20130805-28300-1u5g9dv-0> t.write("test data")          # => 9 IO.read 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

like image 898
Siva Avatar asked Aug 05 '13 07:08

Siva


People also ask

How do I write a Tempfile?

If you want to write text data into a temp file, you can use the writelines() method instead. For using this method, we need to create the tempfile using w+t mode instead of the default w+b mode. To do this, a mode param can be passed to TemporaryFile() to change the mode of the created temp file.

What is Tempfile Ruby?

A utility class for managing temporary files. When you create a Tempfile object, it will create a temporary file with a unique filename. A Tempfile objects behaves just like a File object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc.


1 Answers

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.

like image 159
squiguy Avatar answered Nov 05 '22 01:11

squiguy