Posted almost 10 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.

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Andreas Robecke
Last edit:
almost 6 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 short-lived cookies to improve usability.
Accept or learn more