Ruby tempfiles

Tempfiles get deleted automatically

With the the ruby Tempfile class you can create temporary files. Those files only stick around as long as you have a reference to those. If no more variable points to them, the GC may finalize the object at some point and the file will be removed from the filesystem. If you would try to access your tempfile then using its path (which you stored previously), you would get an error because the file no longer exists.

Unlink your tempfiles when you're done with them

When you are done with your file, you should unlink it, so that it will be removed from the filesystem immediately. If you don't do this, the file will be removed when the object gets finalized as mentioned above. Your tempfile would stick around unnecessarily longer.

Unlink to prevent other processes from accessing your file

On POSIX systems you can use the unlink function right after creation to ensure that only the process which created the file can access it. Because on a POSIX system, as long as you have the file handle, you can access the file even though it is not accessible through the filesystem anymore. Usually you don't want other processes to access your files. Thus you should unlink your tempfiles right after creation if you're on a POSIX system.


If you are using Ruby on Rails, a use case / implementation might look like Rails 3: Sending tempfiles for download.
If a single temporary file is not enough for you, a temp dir might be useful for you.

Andreas Robecke Over 11 years ago