Ruby auto deleting temp file?
I've seen Tempfile
being garbage collected in the same process when I created many temp files to be zipped. In the code below, if I didn't store the Tempfile
handles in the handles
array I would get runtime error (Errno::ENOENT: No such file or directory @ rb_sysopen
) when the Zip::File.open
block closes:
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
From docs:
When a Tempfile object is garbage collected, or when the Ruby interpreter exits, its associated temporary file is automatically deleted.
So, as long as you have your f
in scope, it will not be deleted. If you exit Ruby, it will be deleted. If you are still in Ruby but f
has fallen out of scope, it is indeterminate (probably not deleted, but not guaranteed to exist, and should not be used.)