如何在Ruby中创建临时目录?

时间:2022-09-01 22:47:34

How do I create a temporary directory in Ruby in a nice way? I would also like to delete it automatically on process exit. Thanks!

如何以一种很好的方式在Ruby中创建临时目录?我还想在进程退出时自动删除它。谢谢!

2 个解决方案

#1


33  

See documentation for tmpdir. If mktmpdir method is provided with a block, the temp dir will be removed when block returns. In your case, you would call without a block and handle removal later (=program exit).

请参阅tmpdir的文档。如果为mktmpdir方法提供了一个块,则在块返回时将删除temp dir。在您的情况下,您将在没有块的情况下调用并稍后处理删除(=程序退出)。

Regarding automatic removal on exit, I think tmpdir won't do that for you. However, at_exit should help.

关于退出时自动删除,我认为tmpdir不会为你做那件事。但是,at_exit应该有所帮助。

As an example, Homebrew does it like this:

举个例子,Homebrew就是这样的:

require 'tmpdir'

# rest omitted

TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") do |k|
  dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp")
  at_exit { FileUtils.remove_entry(dir) }
  ENV[k] = dir
end

#2


3  

Use the Dir.mktmpdir method, from the stdlib

使用stdlib中的Dir.mktmpdir方法

#1


33  

See documentation for tmpdir. If mktmpdir method is provided with a block, the temp dir will be removed when block returns. In your case, you would call without a block and handle removal later (=program exit).

请参阅tmpdir的文档。如果为mktmpdir方法提供了一个块,则在块返回时将删除temp dir。在您的情况下,您将在没有块的情况下调用并稍后处理删除(=程序退出)。

Regarding automatic removal on exit, I think tmpdir won't do that for you. However, at_exit should help.

关于退出时自动删除,我认为tmpdir不会为你做那件事。但是,at_exit应该有所帮助。

As an example, Homebrew does it like this:

举个例子,Homebrew就是这样的:

require 'tmpdir'

# rest omitted

TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") do |k|
  dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp")
  at_exit { FileUtils.remove_entry(dir) }
  ENV[k] = dir
end

#2


3  

Use the Dir.mktmpdir method, from the stdlib

使用stdlib中的Dir.mktmpdir方法