Module: Dir::Tmpname

Defined in:
lib/tmpdir.rb

Overview

Temporary name generator

Constant Summary collapse

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



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/tmpdir.rb', line 140

def create(basename, tmpdir=nil, max_try: nil, **opts)
  origdir = tmpdir
  tmpdir ||= tmpdir()
  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



118
119
120
# File 'lib/tmpdir.rb', line 118

def tmpdir
  Dir.tmpdir
end