Siva
Siva

Reputation: 8058

Ruby how to write to Tempfile?

I am trying to create a Tempfile and write some text into it. But I get this strange behavior in 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

Upvotes: 46

Views: 58180

Answers (4)

Artur INTECH
Artur INTECH

Reputation: 7396

It's worth mentioning that calling .rewind is a must or otherwise any subsequent .read call will just return an empty value.

Upvotes: 9

Lev Lukomskyi
Lev Lukomskyi

Reputation: 6677

close or rewind will actually write out content to file. And you may want to delete it after using:

file = Tempfile.new('test_temp')
begin
  file.write <<~FILE
    Test data
    test data
  FILE
  file.close

  puts IO.read(file.path) #=> Test data\ntestdata\n
ensure
  file.delete
end

Upvotes: 10

Debadatt
Debadatt

Reputation: 6015

Try this run t.rewind before read

require 'tempfile'
t = Tempfile.new("test_temp")
t << "Test data"
t.write("test data") # => 9
IO.read t.path # => ""
t.rewind
IO.read t.path # => "Test datatest data"

Upvotes: 25

squiguy
squiguy

Reputation: 33380

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.

Upvotes: 52

Related Questions