Ruby tempfiles

Updated . Posted . Visible to the public. Repeats.

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 file system. In other words: tempfiles are removed automatically. If you would then try to access the tempfile using its path (which you stored previously), you would get an error because the file no longer exists.

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.

Unlinking will 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.

Shared hosting

Note that by default, tempfiles are stored in /tmp, where other system users may see their filenames. The default file permissions of 0600 keep others from reading them, so make sure not to mess with that.

Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2012-09-05 13:17)