Ruby automatically deletes temp file?

I'm confused. Here's my code:

require 'csv'                                                               
require 'tempfile'                                                          

f = Tempfile.new('csv','/tmp')                                                 
f.write 'just wanna test'                                                       
f.close                                                                        

p f.path 

      

If I open the output path, it is empty.

I think this is because TempFile is automatically removed from the filesystem every time the ruby ​​session ends. However, how do I know exactly when the file was deleted? Since I am going to use it to create a temporary file in my rails application, I am afraid the file was deleted before using it.

+6


source to share


3 answers


From the docs:

When the Tempfile object is garbage collected, or when the Ruby interpreter exits, the associated temporary file is automatically deleted.



So, if you have it f

in scope, it will not be removed. If you quit Ruby, it will be removed. If you're still in Ruby but f

out of scope, it is undefined (probably not removed, but not guaranteed to exist and should not be used.)

+12


source


The tempfile is removed by garbage collection (it is no longer referenced and cleaning up frees the object).

As stated in the Ruby documentation :



When the Tempfile object is garbage collected, or when the Ruby interpreter exits, the associated temporary file is automatically deleted ...

As long as you have a reference to a temple object, you don't have to worry about deleting it prematurely.

+5


source


I saw myself Tempfile

collecting garbage in the same process as I created many temporary files for archiving. In the code below, if I didn't store the descriptors Tempfile

in an array handles

, I would get a runtime ( Errno::ENOENT: No such file or directory @ rb_sysopen

) error when the block is Zip::File.open

closed:

handles = []
Zip::File.open(zip_file.path, Zip::File::CREATE) do |zip|
  # there are hundreds of @foos to iterate over
  @foos.each do |foo|
    cit_filename = generate_some_unique_filename
    cit_file = Tempfile.new(cit_filename)
    handles << cit_file
    cit_file.puts('some text')
    cit_file.close
    zip.add(cit_filename, cit_file.path)
  end
end # <- runtime error would have thrown at this point
handles = nil

      

0


source







All Articles