Sha256: c237d5e83f2cf195775dc5cf523d9f3e19455cb69874f382c81b28a3e74e0697

Contents?: true

Size: 1.44 KB

Versions: 80

Compression:

Stored size: 1.44 KB

Contents

require 'fileutils'

module TmpFile

  TMPDIR = "/tmp/#{ENV['USER']}/tmpfiles" 
  FileUtils.mkdir_p TMPDIR unless File.exist? TMPDIR

  def self.tmpdir=(tmpdir)
    TMPDIR.replace tmpdir
    FileUtils.mkdir_p TMPDIR unless File.exist? TMPDIR
  end

  def self.tmpdir
    TMPDIR
  end


  # Creates a random file name, with the given suffix and a random number
  # up to +max+
  def self.random_name(s = "", max = 10000000)
    n = rand(max)
    s + n.to_s
  end

  # Creates a random filename in the temporary directory
  def self.tmp_file(s = "",max=10000000)
    File.join(TMPDIR, random_name(s,max))
  end

  def self.with_file(content = nil, erase = true, options = {})
    options, content, erase = content, nil, true if Hash === content
    options, erase = erase, true if Hash === erase 

    prefix = options[:prefix] || ""
    tmpfile = tmp_file prefix
    if options[:extension]
      tmpfile += ".#{options[:extension]}"
    end

    if IO === content
      Misc.consume_stream(content, false, tmpfile)
    else
      File.open(tmpfile, 'w') do |f| f.write content end if content != nil
    end

    result = yield(tmpfile)

    FileUtils.rm_rf tmpfile if File.exist?(tmpfile) and erase

    result
  end

  def self.with_dir(erase = true, options = {})
    prefix = options[:prefix] || ""
    tmpdir = tmp_file prefix

    FileUtils.mkdir_p tmpdir

    result = yield(tmpdir)

    FileUtils.rm_rf tmpdir if File.exist?(tmpdir) and erase

    result
  end
end

Version data entries

80 entries across 80 versions & 1 rubygems

Version Path
rbbt-util-5.24.0 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.39 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.38 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.37 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.36 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.35 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.34 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.32 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.31 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.30 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.29 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.28 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.27 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.26 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.25 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.24 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.23 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.22 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.21 lib/rbbt/util/tmpfile.rb
rbbt-util-5.23.20 lib/rbbt/util/tmpfile.rb