class Tempfile

A utility class for managing temporary files.

There are two kind of methods of creating a temporary file:

Tempfile.create creates a usual File object. The timing of file deletion is predictable. Also, it supports open-and-unlink technique which removes the temporary file immediately after creation.

Tempfile.new and Tempfile.open creates a Tempfile object. The created file is removed by the GC (finalizer). The timing of file deletion is not predictable.

Synopsis

require 'tempfile'

# Tempfile.create with a block
# The filename are choosen automatically.
# (You can specify the prefix and suffix of the filename by an optional argument.)
Tempfile.create {|f|
  f.puts "foo"
  f.rewind
  f.read                # => "foo\n"
}                       # The file is removed at block exit.

# Tempfile.create without a block
# You need to unlink the file in non-block form.
f = Tempfile.create
f.puts "foo"
f.close
File.unlink(f.path)     # You need to unlink the file.

# Tempfile.create(anonymous: true) without a block
f = Tempfile.create(anonymous: true)
# The file is already removed because anonymous.
f.path                  # => "/tmp/"  (no filename since no file)
f.puts "foo"
f.rewind
f.read                  # => "foo\n"
f.close

# Tempfile.create(anonymous: true) with a block
Tempfile.create(anonymous: true) {|f|
  # The file is already removed because anonymous.
  f.path                # => "/tmp/"  (no filename since no file)
  f.puts "foo"
  f.rewind
  f.read                # => "foo\n"
}

# Not recommended: Tempfile.new without a block
file = Tempfile.new('foo')
file.path      # => A unique filename in the OS's temp directory,
               #    e.g.: "/tmp/foo.24722.0"
               #    This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read      # => "hello world"
file.close
file.unlink    # deletes the temp file

About Tempfile.new and Tempfile.open

This section does not apply to Tempfile.create because it returns a File object (not a Tempfile object).

When you create a Tempfile object, it will create a temporary file with a unique filename. A Tempfile objects behaves just like a File object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc. So although this class does not explicitly document all instance methods supported by File, you can in fact call any File instance method on a Tempfile object.

A Tempfile object has a finalizer to remove the temporary file. This means that the temporary file is removed via GC. This can cause several problems:

There are legacy good practices for Tempfile.new and Tempfile.open as follows.

Explicit close

When a Tempfile object is garbage collected, or when the Ruby interpreter exits, its associated temporary file is automatically deleted. This means that it’s unnecessary to explicitly delete a Tempfile after use, though it’s a good practice to do so: not explicitly deleting unused Tempfiles can potentially leave behind a large number of temp files on the filesystem until they’re garbage collected. The existence of these temp files can make it harder to determine a new Tempfile filename.

Therefore, one should always call unlink or close in an ensure block, like this:

file = Tempfile.new('foo')
begin
   # ...do something with file...
ensure
   file.close
   file.unlink   # deletes the temp file
end

Tempfile.create { … } exists for this purpose and is more convenient to use. Note that Tempfile.create returns a File instance instead of a Tempfile, which also avoids the overhead and complications of delegation.

Tempfile.create('foo') do |file|
   # ...do something with file...
end

Unlink after creation

On POSIX systems, it’s possible to unlink a file right after creating it, and before closing it. This removes the filesystem entry without closing the file handle, so it ensures that only the processes that already had the file handle open can access the file’s contents. It’s strongly recommended that you do this if you do not want any other processes to be able to read from or write to the Tempfile, and you do not need to know the Tempfile’s filename either.

Also, this guarantees the temporary file is removed even if Ruby exits abnormally. The OS reclaims the storage for the temporary file when the file is closed or the Ruby process exits (normally or abnormally).

For example, a practical use case for unlink-after-creation would be this: you need a large byte buffer that’s too large to comfortably fit in RAM, e.g. when you’re writing a web server and you want to buffer the client’s file upload data.

‘Tempfile.create(anonymous: true)` supports this behavior. It also works on Windows.

Minor notes

Tempfile’s filename picking method is both thread-safe and inter-process-safe: it guarantees that no other threads or processes will pick the same filename.

Tempfile itself however may not be entirely thread-safe. If you access the same Tempfile object from multiple threads then you should protect it with a mutex.