Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create temp dir in Ruby?

Tags:

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!

like image 881
lzap Avatar asked Jul 27 '11 08:07

lzap


2 Answers

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).

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

As an example, Homebrew does it like this:

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
like image 63
merryprankster Avatar answered Nov 18 '22 08:11

merryprankster


Use the Dir.mktmpdir method, from the stdlib:

require 'tmpdir'
Dir.mktmpdir do |d|
  File.open("#{d}/1.txt", 'w') do |f|
    f.write('1.txt') 
  end
end
# at this point 1.txt and the dir no longer exist
like image 27
marto Avatar answered Nov 18 '22 10:11

marto