The case of the mysteriously disappearing file
If you want a temporary filename in Ruby, you might be tempted
to use Tempfile
to generate it, rather like this:
def unique_temp_filename tempfile = Tempfile.new('some_prefix') path = tempfile.path tempfile.close path end
Although that mostly works, it has an interesting bug. When the
Tempfile
instance is collected by the garbage
collector, the file on disk is deleted (or unlinked in system
parlance), as the documentation advises:
If you don’t explicitly unlink the temporary file, the removal will be delayed until the object is finalized.
This means that your temporary file will be deleted from disk at an unknown time in the future when the garbage collector runs. That’s almost certainly not what you want, as you’ll then spend some time tracking down a puzzling bug.
The solution is to use tempfile.close!
, which
unlinks the file immediately, in place of
tempfile.close
. You can subsequently use the released
filename with impunity.