Temp dir with ruby

Played around with few programming languages to handle temp dirs, but amongst the lot /me really liked ruby's paradigm.

Mainly liked :

  • yield for the win!

  • Easy maintenance of code.

  • Temp dir removal is assured.

Code to manage temp dir :

def in_tmp
  path = File.expand_path "#{Dir.tmpdir}/#{Time.now.to_i}#{rand(1000)}/"
  FileUtils.mkdir_p( path )
  yield( path )
  # This ensures temp dir removal.
  FileUtils.rm_rf( path ) if File.exists?( path )

The above method can be used as :

in_tmp do |tmpdir|
  puts "In tmp dir: #{tmpdir}"

This code was improved with the help of a few hackers at #ruby, anyway there might be better ways to do this, do suggest your way below! Happy Hacking.

Share this