End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Tempfile.create
# File tmp/rubies/ruby-3.1.3/lib/tempfile.rb, line 349
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 temporary file as a usual File object (not a Tempfile). It does not use finalizer and delegation, which makes it more efficient and reliable.
If no block is given, this is similar to Tempfile.new except creating File instead of Tempfile. In that case, the created file is not removed automatically. You should use File.unlink to remove it.
If a block is given, then a File object will be constructed, and the block is invoked with the object as the argument. The File object will be automatically closed and the temporary file is removed after the block terminates, releasing all resources that the block created. The call returns the value of the block.
In any case, all arguments (basename, tmpdir, mode, and **options) will be treated the same as for Tempfile.new.
Tempfile.create('foo', '/home/temp') do |f| # ... do something with f ... end