Creating a thread-safe temporary file name

后端 未结 4 739
既然无缘
既然无缘 2020-12-29 21:18

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 ther

4条回答
  •  情歌与酒
    2020-12-29 21:41

    Since Dir::Tmpname.make_tmpname was removed in Ruby 2.5.0, this one falls back to using SecureRandom:

    require "tmpdir"
    
    def generate_temp_filename(ext=".png")
      filename = begin
        Dir::Tmpname.make_tmpname(["x", ext], nil)
      rescue NoMethodError
        require "securerandom"
        "#{SecureRandom.urlsafe_base64}#{ext}"
      end
      File.join(Dir.tmpdir, filename)
    end
    

提交回复
热议问题