Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 342
Mike Avatar asked Jul 16 '09 18:07

Mike


People also ask

How do you create a temp file in Ruby?

A utility class for managing temporary files. When you create a Tempfile object, it will create a temporary file with a unique filename. A Tempfile objects behaves just like a File object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc.

What is $Tmpdir?

TMPDIR is the canonical environment variable in Unix and POSIX that should be used to specify a temporary directory for scratch space. Most Unix programs will honor this setting and use its value to denote the scratch area for temporary files instead of the common default of /tmp or /var/tmp.


2 Answers

The Dir object has a method mktmpdir which creates a temporary directory:

require 'tmpdir' # Not needed if you are using rails.  Dir.mktmpdir do |dir|   puts "My new temp dir: #{dir}" end 

The temporary directory will be removed after execution of the block.

like image 102
Justin Tanner Avatar answered Sep 18 '22 14:09

Justin Tanner


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

like image 39
slillibri Avatar answered Sep 16 '22 14:09

slillibri