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

后端 未结 9 609

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.

9条回答
  •  一整个雨季
    2020-12-28 13:28

    A general aprox I'm using now:

    def in_tmpdir
      path = File.expand_path "#{Dir.tmpdir}/#{Time.now.to_i}#{rand(1000)}/"
      FileUtils.mkdir_p path
      yield path
    ensure
      FileUtils.rm_rf( path ) if File.exists?( path )
    end
    

    So in your code you can:

    in_tmpdir do |tmpdir|
      puts "My tmp dir: #{tmpdir}"
      # work with files in the dir
    end
    

    The temporary dir will be removed automatically when your method will finish.

提交回复
热议问题