Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Tempfile doesn't Create File on Disk

I'm currently running this code on Ruby.

file = Tempfile.new(['tempemail', '.html'])
file << email # Email is a Ruby String (not nil)

Launchy.open(file.path)

Launchy is complaining that the file does not exist. I've run cat and confirmed this. Is there some way to force Ruby to save the Tempfile to disk?

EDIT:

I've done one additional test. I added a file.rewind and file.read before Launchy.open. The file successfully has the contents of email.

like image 885
Astephen2 Avatar asked Dec 30 '14 23:12

Astephen2


1 Answers

Can you try a file.close.

Test without Launchy:

require 'tempfile'
file = Tempfile.new(['tempemail', '.html'])
file << 'xx' # Email is a Ruby String (not nil)

file.close #<- This is needed

p File.read(file.path) # -> 'xx'

Without the file.close you get an empty string.

Instead of close you may also use flush if you continue to write data into the file:

require 'tempfile'
file = Tempfile.new(['tempemail', '.html'])
file << "xx\n" # Email is a Ruby String (not nil)

p file.path
file.flush

file << "yy\n" # Email is a Ruby String (not nil)
file.flush

p File.read(file.path)
like image 85
knut Avatar answered Nov 09 '22 23:11

knut