Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Tempfile.new
# File tmp/rubies/ruby-4.1.0-preview1/lib/tempfile.rb, line 219
def initialize(basename="", tmpdir=nil, mode: 0, **options)
warn "Tempfile.new doesn't call the given block.", uplevel: 1 if block_given?
@unlinked = false
@mode = mode|File::RDWR|File::CREAT|File::EXCL
tmpfile = nil
::Dir::Tmpname.create(basename, tmpdir, **options) do |tmpname, n, opts|
opts[:perm] = 0600
tmpfile = File.open(tmpname, @mode, **opts)
@opts = opts.freeze
end
super(tmpfile)
@finalizer_manager = FinalizerManager.new(__getobj__.path)
@finalizer_manager.register(self, __getobj__)
end
Creates a file in the underlying file system; returns a new Tempfile object based on that file.
If possible, consider instead using Tempfile.create, which:
-
Avoids the performance cost of delegation, incurred when
Tempfile.newcalls its superclassDelegateClass(File). -
Does not rely on a finalizer to close and unlink the file, which can be unreliable.
Creates and returns file whose:
-
Class is Tempfile (not File, as in
Tempfile.create). -
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).
The underlying file is removed when the Tempfile object dies and is reclaimed by the garbage collector.
Example:
f = Tempfile.new # => #<Tempfile:/tmp/20220505-17839-1s0kt30> f.class # => Tempfile f.path # => "/tmp/20220505-17839-1s0kt30" 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.new('foo') # => #<Tempfile:/tmp/foo20220505-17839-1whk2f>
-
An array of two strings
[prefix, suffix]: the generated filename begins withprefixand ends withsuffix:ExampleTempfile.new(%w/foo .jpg/) # => #<Tempfile:/tmp/foo20220505-17839-58xtfi.jpg>
With arguments basename and tmpdir, the file is created in directory tmpdir:
Tempfile.new('foo', '.') # => #<Tempfile:./foo20220505-17839-xfstr8>
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.
Related: Tempfile.create.