Method: Tempfile#initialize

Defined in:
lib/tempfile.rb

#initialize(basename = "", tmpdir = nil, mode: 0, **options) ⇒ Tempfile

Creates a temporary file with permissions 0600 (= only readable and writable by the owner) and opens it with mode “w+”.

It is recommended to use Tempfile.create { … } instead when possible, because that method avoids the cost of delegation and does not rely on a finalizer to close and unlink the file, which is unreliable.

The basename parameter is used to determine the name of the temporary file. You can either pass a String or an Array with 2 String elements. In the former form, the temporary file’s base name will begin with the given string. In the latter form, the temporary file’s base name will begin with the array’s first element, and end with the second element. For example:

file = Tempfile.new('hello')
file.path  # => something like: "/tmp/hello2843-8392-92849382--0"

# Use the Array form to enforce an extension in the filename:
file = Tempfile.new(['hello', '.jpg'])
file.path  # => something like: "/tmp/hello2843-8392-92849382--0.jpg"

The temporary file will be placed in the directory as specified by the tmpdir parameter. By default, this is Dir.tmpdir.

file = Tempfile.new('hello', '/home/aisaka')
file.path  # => something like: "/home/aisaka/hello2843-8392-92849382--0"

You can also pass an options hash. Under the hood, Tempfile creates the temporary file using File.open. These options will be passed to File.open. This is mostly useful for specifying encoding options, e.g.:

Tempfile.new('hello', '/home/aisaka', encoding: 'ascii-8bit')

# You can also omit the 'tmpdir' parameter:
Tempfile.new('hello', encoding: 'ascii-8bit')

Note: mode keyword argument, as accepted by Tempfile, can only be numeric, combination of the modes defined in File::Constants.

Exceptions

If Tempfile.new cannot find a unique filename within a limited number of tries, then it will raise an exception.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/tempfile.rb', line 134

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
  ::Dir::Tmpname.create(basename, tmpdir, **options) do |tmpname, n, opts|
    opts[:perm] = 0600
    @tmpfile = File.open(tmpname, @mode, **opts)
    @opts = opts.freeze
  end
  ObjectSpace.define_finalizer(self, Remover.new(@tmpfile))

  super(@tmpfile)
end