Posted almost 7 years ago. Visible to the public. Repeats.

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.

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.

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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Andreas Robecke
Last edit:
almost 3 years ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Andreas Robecke to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more