views:

279

answers:

3

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, so something like this won't work.

+1  A: 

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

slillibri
That gives the OS's global temp path, but not your app's own dedicated, empty path.
Mike
Agree with Mike, I don't think this is a correct answer to the above question. What we need is similar to Tempfile (http://ruby-doc.org/stdlib/libdoc/tempfile/rdoc/files/tempfile_rb.html), but for dirs; ideally the Tempfile supporting dirs directly.
inger
A: 

I started to tackle this by hijacking Tempfile, see below. It should clean itself up as Tempfile does, but doesn't always yet.. It's yet to delete files in the tempdir. Anyway I share this here, might be useful as a starting point.

require 'tempfile'
class Tempdir < Tempfile
  require 'tmpdir'
  def initialize(basename, tmpdir = Dir::tmpdir)
    super
    p = self.path
    File.delete(p)
    Dir.mkdir(p)
  end
  def unlink # copied from tempfile.rb
    # keep this order for thread safeness
    begin
      Dir.unlink(@tmpname) if File.exist?(@tmpname)
      @@cleanlist.delete(@tmpname)
      @data = @tmpname = nil
      ObjectSpace.undefine_finalizer(self)
    rescue Errno::EACCES
      # may not be able to unlink on Windows; just ignore
    end
  end  
end

This can be used the same way as Tempfile, eg:

 Tempdir.new('foo')

All methods on Tempfile , and in turn, File should work. Just briefly tested it, so no guarantees.

inger
A: 

Check out the Ruby STemp library: http://ruby-stemp.rubyforge.org/rdoc/

If you do something like this:

dirname = STemp.mkdtemp("#{Dir.tmpdir}/directory-name-template-XXXXXXXX")

dirname will be a string that points to a directory that's guaranteed not to exist previously. You get to define what you want the directory name to start with. The X's get replaced with random characters.

JT