What is the best way to get an empty temporary directory in Ruby on Rails?

Viewed 33286

What is the best way to get a temporary directory with nothing in it using Ruby on Rails? I need the API to be cross-platform compatible. The stdlib tmpdir won't work.

9 Answers

The Dir#tmpdir function in the Ruby core (not stdlib that you linked to) should be cross-platform.

To use this function you need to require 'tmpdir'.

Ruby has Dir#mktmpdir, so just use that.

require 'tempfile'
Dir.mktmpdir('prefix_unique_to_your_program') do |dir|
    ### your work here ###
end

See http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tmpdir/rdoc/Dir.html

Or build your own using Tempfile tempfile that is process and thread unique, so just use that to build a quick Tempdir.

require 'tempfile'
Tempfile.open('prefix_unique_to_your_program') do |tmp|
  tmp_dir = tmp.path + "_dir"
  begin
    FileUtils.mkdir_p(tmp_dir)

    ### your work here ###
  ensure
    FileUtils.rm_rf(tmp_dir)
  end
end

See http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html for optional suffix/prefix options.

Related