Sha256: 15e9684cb1455358c4d3ed137ffbb05a58868bd9fc465948cc057c48aca34186

Contents?: true

Size: 1.24 KB

Versions: 89

Compression:

Stored size: 1.24 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
    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 = {})
    tmpfile = tmp_file
    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 = {})
    tmpdir = tmp_file

    FileUtils.mkdir_p tmpdir

    result = yield(tmpdir)

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

    result
  end
end

Version data entries

89 entries across 89 versions & 1 rubygems

Version Path
rbbt-util-5.21.94 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.93 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.92 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.91 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.90 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.89 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.87 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.86 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.85 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.84 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.83 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.81 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.80 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.78 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.77 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.76 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.75 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.74 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.73 lib/rbbt/util/tmpfile.rb
rbbt-util-5.21.72 lib/rbbt/util/tmpfile.rb