lzap lzap - 1 year ago 114
Ruby Question

How to create temp dir in 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!

Answer Source

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

  dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp")
  at_exit { FileUtils.remove_entry(dir) }
  ENV[k] = dir
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download