"creating a thread-safe temporary file name" Code Answer

3

dir::tmpname.create

you could use dir::tmpname.create. it figures out what temporary directory to use (unless you pass it a directory). it's a little ugly to use given that it expects a block:

require 'tmpdir'
# => true
dir::tmpname.create(['prefix-', '.ext']) {}
# => "/tmp/prefix-20190827-1-87n9iu.ext"
dir::tmpname.create(['prefix-', '.ext'], '/my/custom/directory') {}
# => "/my/custom/directory/prefix-20190827-1-11x2u0h.ext"

the block is there for code to test if the file exists and raise an errno::eexist so that a new name can be generated with incrementing value appended on the end.

the rails solution

the solution implemented by ruby on rails is short and similar to the solution originally implemented in ruby:

require 'tmpdir'
# => true
file.join(dir.tmpdir, "your_prefix-#{time.now.strftime("%y%m%d")}-#{$$}-#{rand(0x100000000).to_s(36)}-your_suffix")
=> "/tmp/your_prefix-20190827-1-wyouwg-your_suffix"
file.join(dir.tmpdir, "your_prefix-#{time.now.strftime("%y%m%d")}-#{$$}-#{rand(0x100000000).to_s(36)}-your_suffix")
=> "/tmp/your_prefix-20190827-1-140far-your_suffix"

dir::tmpname.make_tmpname (ruby 2.5.0 and earlier)

dir::tmpname.make_tmpname was removed in ruby 2.5.0. prior to ruby 2.4.4 it could accept a directory path as a prefix, but as of ruby 2.4.4, directory separators are removed.

digging in tempfile.rb you'll notice that tempfile includes dir::tmpname. inside you'll find make_tmpname which does what you ask for.

require 'tmpdir'
# => true
file.join(dir.tmpdir, dir::tmpname.make_tmpname("prefix-", nil))
# => "/tmp/prefix-20190827-1-dfhvld"
file.join(dir.tmpdir, dir::tmpname.make_tmpname(["prefix-", ".ext"], nil))
# => "/tmp/prefix-20190827-1-19zjck1.ext"
file.join(dir.tmpdir, dir::tmpname.make_tmpname(["prefix-", ".ext"], "suffix"))
# => "/tmp/prefix-20190827-1-f5ipo7-suffix.ext"
By vmoravec on August 13 2022

Answers related to “creating a thread-safe temporary file name”

Only authorized users can answer the Search term. Please sign in first, or register a free account.