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 ) ensure # This ensures temp dir removal. FileUtils.rm_rf( path ) if File.exists?( path ) end
The above method can be used as :
in_tmp do |tmpdir| puts “In tmp dir: #{tmpdir}” end
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.
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.