本文介绍了如何在 Ruby 中创建临时目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以一种不错的方式在 Ruby 中创建临时目录?我还想在进程退出时自动删除它.谢谢!
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!
推荐答案
请参阅 tmpdir.如果 mktmpdir
方法被提供给一个块,当块返回时临时目录将被删除.在您的情况下,您将在没有块的情况下调用并稍后处理删除(=程序退出).
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 不会为您做到这一点.但是,at_exit 应该会有所帮助.
Regarding automatic removal on exit, I think tmpdir won't do that for you. However, at_exit should help.
例如,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
这篇关于如何在 Ruby 中创建临时目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!