Fork me on GitHub

Project Notes

Using Temporary Files with Ruby


The Tempfile class in the ruby standard library provides a simple interface for creating and managing temporary files.

File Name Generation

Tempfile provides threadsafe generation of unique filenames, and accepts hints on the base name, path and extension:'foo').path
 => "/var/folders/28/_tsmhg4172s_wy7vswfkzq9h0000gn/T/foo20190720-858-2bg33b"'foo', '/var/folders/28/_tsmhg4172s_wy7vswfkzq9h0000gn/T').path
 => "/var/folders/28/_tsmhg4172s_wy7vswfkzq9h0000gn/T/foo20190720-858-tp775f"['foo', '.jpg']).path
 => "/var/folders/28/_tsmhg4172s_wy7vswfkzq9h0000gn/T/foo20190720-858-bry74e.jpg"

Cleaning Up Files

Tempfile automatically removes tempfiles after the tempfile handle is out of scope and the garbage collector runs.

Explicitly removing generated files is possible, and probably a good idea if many temp files are being created. This can be performed with unlink, close(true) or close! methods.

If one wants to generate a temp file and prevent it’s automatic removal, one technique is to undefine the finalizer on the tempfile handle: ObjectSpace.undefine_finalizer(file)

Running Some Tests

tempfiles_test.rb demonstrates a number of ways of working with Tempfiles, including implicit and explcit file cleanup approaches.

$ ruby tempfiles_test.rb
Run options: --seed 42461

# Running:


Finished in 0.006527s, 459.6146 runs/s, 2451.2778 assertions/s.

3 runs, 16 assertions, 0 failures, 0 errors, 0 skips

Credits and References

About LCK#68 ruby
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.