Ruby how to write to Tempfile
Solution 1
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.
Solution 2
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"
Solution 3
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
Solution 4
It's worth mentioning, calling .rewind
is a must otherwise any subsequent .read
call will just return empty value
Siva
“Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.” - Eric Raymond
Updated on July 21, 2022Comments
-
Siva almost 2 years
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 emptyAm 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
-
vgoff over 10 yearsPrefer to use blocks for file operations if possible, you won't have to remember to close it, it will do it for you. Using certain methods will also automatically close it or you as well.
IO.read
(File.read
) is one of these methods, according to the documentation. "read ensures the file is closed before returning." -
glasz about 10 yearsrewind makes sense when you want to reuse the file descriptor later, e.g.,
Zip::File.open(f)
. else, it'll complain about closed file. -
songyy almost 9 yearsWhy do u still need
t << "Test data"
? -
Elliott over 6 yearsI am pretty new to ruby and I had a similar issue here. I missed this issue I think because on a local machine it seemed to be working whereas when I test on a build server I was hitting the same issue. Any idea why this would fail intermittently? I am going to search around more as well but wanted to ask here first.