Temporary files

suggest change

Ruby's standard library provides the tempfile and tmpdir modules to safely create temporary files and directories with unique names, secure file permissions, and automatic cleanup.

Tempfile.create creates a temporary file on disk. When passed a block, it automatically closes and unlinks (deletes) the file as soon as the block terminates, even if an exception is raised:

require 'tempfile'

# Tempfile.create automatically unlinks when the block exits
Tempfile.create(['report', '.csv']) do |temp|
  puts "Temporary file path: #{temp.path}"

  # Write data
  temp.write("id,name,role\n")
  temp.write("1,Alice,Admin\n")

  # Rewind to read back from the beginning
  temp.rewind
  puts "Content:\n#{temp.read}"
end

# File is automatically deleted once outside the block

The first argument specifies the filename prefix and optional suffix/extension: ['prefix', '.ext'].

Using Tempfile.new

If you need the temporary file to persist across multiple methods or scopes, use Tempfile.new. You must explicitly close and unlink it when finished, though Ruby's garbage collector and at_exit handlers attempt to delete it when the object is finalized:

require 'tempfile'

file = Tempfile.new('download')
begin
  file.write("Downloaded binary content")
  file.flush

  puts "File created at: #{file.path}"
  # Process the file...
ensure
  file.close
  file.unlink # Deletes the file immediately from the filesystem
end

Creating Temporary Directories with Dir.mktmpdir

When an operation requires generating multiple related files (such as unpacking an archive or building an artifact), use Dir.mktmpdir from the tmpdir library:

require 'tmpdir'

Dir.mktmpdir('build-task-') do |dir|
  puts "Temporary directory: #{dir}"

  file_a = File.join(dir, 'output.txt')
  File.write(file_a, "Generated data")

  file_b = File.join(dir, 'metadata.json')
  File.write(file_b, '{"status": "ok"}')

  puts "Created files: #{Dir.entries(dir).reject { |f| f.start_with?('.') }}"
end
# Entire directory and all contained files are recursively deleted here

Specifying Custom Directories and Encoding

By default, files are created in the system temporary directory (e.g., /tmp or C:\Users\...\AppData\Local\Temp). You can specify an alternative parent directory and encoding:

require 'tempfile'
require 'fileutils'

FileUtils.mkdir_p('./custom_tmp') # the parent directory must already exist
Tempfile.create(['data-', '.bin'], './custom_tmp', binmode: true) do |file|
  file.write("\x00\xFF\xFE\x01".b)
  file.rewind
  puts "Wrote #{file.size} bytes in binary mode"
end

Security Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents