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
Since you only need the filename, what about using the SecureRandom for that:
You can also use
SecureRandom.alphanumeric
I found the Dir:Tmpname solution did not work for me. When evaluating this:
Under MRI Ruby 1.9.3p194 I get:
Under JRuby 1.7.5 (1.9.3p393) I get:
You might try something like this:
Digging in
tempfile.rb
you'll notice thatTempfile
includesDir::Tmpname
. Inside you'll findmake_tmpname
which does what you ask for.In the same file, there's also
Dir::Tmpname.create
which, depending on what you want to achieve, does a little more thanmake_tmpname
. In particular, it figures out what temporary directory to use (assuming you're not on *nix where/tmp
is a globally correct assumption). Still, 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::EEXIST
so that a new name can be generated with incrementing value tagged on the end.