Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
Tempfile.create
# File tmp/rubies/ruby-3.3.0/lib/tempfile.rb, line 438
def Tempfile.create(basename="", tmpdir=nil, mode: 0, **options)
tmpfile = nil
Dir::Tmpname.create(basename, tmpdir, **options) do |tmpname, n, opts|
mode |= File::RDWR|File::CREAT|File::EXCL
opts[:perm] = 0600
tmpfile = File.open(tmpname, mode, **opts)
end
if block_given?
begin
yield tmpfile
ensure
unless tmpfile.closed?
if File.identical?(tmpfile, tmpfile.path)
unlinked = File.unlink tmpfile.path rescue nil
end
tmpfile.close
end
unless unlinked
begin
File.unlink tmpfile.path
rescue Errno::ENOENT
end
end
end
else
tmpfile
end
end
Creates a file in the underlying file system; returns a new File object based on that file.
With no block given and no arguments, creates and returns file whose:
-
Directory is the system temporary directory (system-dependent).
-
Generated filename is unique in that directory.
-
Permissions are
0600; see File Permissions. -
Mode is
'w+'(read/write mode, positioned at the end).
With no block, the file is not removed automatically, and so should be explicitly removed.
Example:
f = Tempfile.create # => #<File:/tmp/20220505-9795-17ky6f6> f.class # => File f.path # => "/tmp/20220505-9795-17ky6f6" f.stat.mode.to_s(8) # => "100600" File.exist?(f.path) # => true File.unlink(f.path) File.exist?(f.path) # => false
Argument basename, if given, may be one of:
-
A string: the generated filename begins with
basename:ExampleTempfile.create('foo') # => #<File:/tmp/foo20220505-9795-1gok8l9>
-
An array of two strings
[prefix, suffix]: the generated filename begins withprefixand ends withsuffix:ExampleTempfile.create(%w/foo .jpg/) # => #<File:/tmp/foo20220505-17839-tnjchh.jpg>
With arguments basename and tmpdir, the file is created in directory tmpdir:
Tempfile.create('foo', '.') # => #<File:./foo20220505-9795-1emu6g8>
Keyword arguments mode and options are passed directly to method File.open:
-
The value given with
modemust be an integer, and may be expressed as the logical OR of constants defined inFile::Constants. -
For
options, see Open Options.
With a block given, creates the file as above, passes it to the block, and returns the block’s value; before the return, the file object is closed and the underlying file is removed:
Tempfile.create {|file| file.path } # => "/tmp/20220505-9795-rkists"
Related: Tempfile.new.