Module: Dir::Tmpname

Defined in:
lib/tmpdir.rb

Overview

Temporary name generator

Constant Summary collapse

TMPDIR_CANDIDATES =

Temporary directory candidates consisting of environment variable names or description and path pairs.

'TMPDIR', 'TMP', 'TEMP',
  ['system temporary path', systmpdir],
  %w[/tmp /tmp],
  %w[. .],
].each(&:freeze).freeze
UNUSABLE_CHARS =

Unusable characters as path name

"^,-.0-9A-Z_a-z~"

Class Method Summary collapse

Class Method Details

.create(basename, tmpdir = nil, max_try: nil, **opts) ⇒ Object

Generates and yields random names to create a temporary name



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/tmpdir.rb', line 159

def create(basename, tmpdir=nil, max_try: nil, **opts)
  if tmpdir
    origdir = tmpdir = File.path(tmpdir)
    raise ArgumentError, "empty parent path" if tmpdir.empty?
  else
    tmpdir = tmpdir()
  end
  n = nil
  prefix, suffix = basename
  prefix = (String.try_convert(prefix) or
            raise ArgumentError, "unexpected prefix: #{prefix.inspect}")
  prefix = prefix.delete(UNUSABLE_CHARS)
  suffix &&= (String.try_convert(suffix) or
              raise ArgumentError, "unexpected suffix: #{suffix.inspect}")
  suffix &&= suffix.delete(UNUSABLE_CHARS)
  begin
    t = Time.now.strftime("%Y%m%d")
    path = "#{prefix}#{t}-#{$$}-#{RANDOM.next}"\
           "#{n ? %[-#{n}] : ''}#{suffix||''}"
    path = File.join(tmpdir, path)
    yield(path, n, opts, origdir)
  rescue Errno::EEXIST
    n ||= 0
    n += 1
    retry if !max_try or n < max_try
    raise "cannot generate temporary name using '#{basename}' under '#{tmpdir}'"
  end
  path
end

.tmpdirObject



137
138
139
# File 'lib/tmpdir.rb', line 137

def tmpdir
  Dir.tmpdir
end