On Oct 23, 2008, at 2:24 PM, Kenneth McDonald wrote:

> I'd like to be able to obtain a temporary directory in the same way  
> I can easily obtain a temporary file, but there doesn't seem to be a  
> function for this. Currently, I'm creating a temp file, getting it's  
> name, unlinking it, and then creating a dir with the same name. But  
> this is ugly, and in theory subject to a race condition. Is there a  
> better way of doing this?
>
> Thanks,
> Ken
>



this keeps backwards compact, but also lets you do

   Dir.tmpdir do

     puts "in tmpdir #{ Dir.pwd }"

   end


the tmpdir will be created for you and cleaned up too





class Dir
   module Tmpdir
     require 'tmpdir'
     require 'socket'
     require 'fileutils'

     unless defined?(Super)
       Super = Dir.send(:method, :tmpdir)
       class << Dir
         remove_method :tmpdir
       end
     end

     class Error < ::StandardError; end

     Hostname = Socket.gethostname || 'localhost'
     Pid = Process.pid
     Ppid = Process.ppid

     def tmpdir *args, &block
       options = Hash === args.last ? args.pop : {}

       dirname = Super.call(*args)

       return dirname unless block

       turd = options['turd'] || options[:turd]

       basename = [
         Hostname,
         Ppid,
         Pid,
         Thread.current.object_id.abs,
         rand
       ].join('-')

       pathname = File.join dirname, basename

       made = false

       42.times do
         begin
           FileUtils.mkdir_p pathname
           break(made = true)
         rescue Object
           sleep rand
           :retry
         end
       end

       raise Error, "failed to make tmpdir in #{ dirname.inspect }"  
unless made

       begin
         return Dir.chdir(pathname, &block)
       ensure
         unless turd
           FileUtils.rm_rf(pathname) if made
         end
       end
     end
   end

   extend Tmpdir
end




a @ http://codeforpeople.com/
--
we can deny everything, except that we have the possibility of being  
better. simply reflect on that.
h.h. the 14th dalai lama