When using Tempfile Ruby is creating a file with a thread-safe and inter-process-safe name. I only need a file name in that way.
I was wondering if there is a more straight forward approach way than:
t = Tempfile.new(['fleischwurst', '.png'])
temp_path = t.path
t.close
t.unlink
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:The block is there for code to test if the file exists and raise an
Errno::EEXISTso 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:
Dir::Tmpname.make_tmpname (Ruby 2.5.0 and earlier)
Digging in
tempfile.rbyou’ll notice thatTempfileincludesDir::Tmpname. Inside you’ll findmake_tmpnamewhich does what you ask for.