创建一个线程安全的临时文件名 [英] Creating a thread-safe temporary file name

查看:119
本文介绍了创建一个线程安全的临时文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Tempfile时,Ruby将使用线程安全和进程间安全的名称创建文件.我只需要一个文件名.

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

您可以使用Dir::Tmpname.create.它指出要使用的临时目录(除非您将目录传递给它).鉴于它需要一个块,所以使用起来有点难看:

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"

该代码块用于测试文件是否存在并引发Errno::EEXIST,以便可以生成新名称,并在末尾附加递增值.

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.

Ruby on Rails 实施的解决方案简短且类似于解决方案最初是在Ruby中实现的:

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和更早版本)

Dir :: Tmpname.make_tmpname在Ruby 2.5.0中已删除.在Ruby 2.4.4之前,它可以接受目录路径作为前缀,但是从Ruby 2.4.4开始,将删除目录分隔符.

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.

tempfile.rb中进行挖掘,您会发现Tempfile包括Dir::Tmpname.在内部,您会发现 make_tmpname 可以满足您的要求

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"

这篇关于创建一个线程安全的临时文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆