Module: Dir::Tmpname

Defined in:
lib/tmpdir.rb

Overview

:nodoc:

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

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



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/tmpdir.rb', line 128

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



114
115
116
# File 'lib/tmpdir.rb', line 114

def tmpdir
  Dir.tmpdir
end