Tuesday, June 17, 2008

'Temp'ting

I was working on a personal project. I needed to create my outputs in temporary folder. How do we get the temporary folder path in Ruby?

In Windows, we have an environment variable named TMP or TEMP to point to the temporary folder path. In order to access environment variables, Ruby defines ENV object. So

ENV['TMP']

would get me the temporary folder path. But this is windows only. Linux need not have this environment variable defined. So we need some other portable technique.

As you would know, it is easy to create a temporary file using Tempfile.

require 'tempfile'
tmp = Tempfile.new('foo')

It is portable way of creating a temporary file. A temporary file will be created in temporary directory. Tempfile also has a neat path method which would help us.

require 'tempfile'
tmp_path = Tempfile.new('foo').path # we got the temporary directory for any platform

But wait. Creating a dummy file just to get temporary folder path? Yuk. There must be a better way. Hey, you know what? There is a better way.

I almost forgot Ruby is open source. We could take a look at tempfile and see how they did it. Here is what we get. I simplified it a little bit for readability.

require 'tmpdir'
class Tempfile
  def initialize(basename, tmpdir=Dir::tmpdir)
  end
end

We have tmpdir library, which has a neat Dir::tmpdir just fit for our purpose. Let's just try it out with our little friend irb:

irb(main):008:0> require 'tmpdir'
=> true
irb(main):009:0> Dir::tmpdir
=> "/tmp"

I got what I want. I don't have time to snoop around further and see how Dir::tmpdir gets the temp path portably. May be some other time...

No comments: