Method: Tempfile#initialize
- Defined in:
- lib/tempfile.rb
#initialize(basename = "", tmpdir = nil, mode: 0, **options) ⇒ Tempfile
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.new calls its superclass
DelegateClass(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
:Tempfile.new('foo') # => #<Tempfile:/tmp/foo20220505-17839-1whk2f>
-
An array of two strings
[prefix, suffix]
: the generated filename begins withprefix
and ends withsuffix
:Tempfile.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
mode
must be an integer, and may be expressed as the logical OR of constants defined in File::Constants. -
For
options
, see Open Options.
Related: Tempfile.create.
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/tempfile.rb', line 219 def initialize(basename="", tmpdir=nil, mode: 0, **) 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, **) 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 |