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

后端 未结 9 615

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:26

    Ruby has Dir#mktmpdir, so just use that.

    require 'tempfile'
    Dir.mktmpdir('prefix_unique_to_your_program') do |dir|
        ### your work here ###
    end
    

    See http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tmpdir/rdoc/Dir.html

    Or build your own using Tempfile tempfile that is process and thread unique, so just use that to build a quick Tempdir.

    require 'tempfile'
    Tempfile.open('prefix_unique_to_your_program') do |tmp|
      tmp_dir = tmp.path + "_dir"
      begin
        FileUtils.mkdir_p(tmp_dir)
    
        ### your work here ###
      ensure
        FileUtils.rm_rf(tmp_dir)
      end
    end
    

    See http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html for optional suffix/prefix options.

提交回复
热议问题