Sha256: afa6ac84ebf5cf36b45832797f74bd92220c515d00529e92511906404e9023e8

Contents?: true

Size: 857 Bytes

Versions: 4

Compression:

Stored size: 857 Bytes

Contents

require 'fileutils'

module TmpFile

  TMPDIR = "/tmp/tmpfiles" 
  FileUtils.mkdir TMPDIR unless File.exist? TMPDIR

  def self.tmpdir=(tmpdir)
    TMPDIR.replace tmpdir
    FileUtils.mkdir 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)
    tmpfile = tmp_file

    File.open(tmpfile, 'w') do |f| f.write content end if content != nil

    result = yield(tmpfile)

    FileUtils.rm tmpfile if File.exists?(tmpfile) and erase

    result
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rbbt-util-2.0.1 lib/rbbt/util/tmpfile.rb
rbbt-util-1.2.1 lib/rbbt/util/tmpfile.rb
rbbt-util-1.1.0 lib/rbbt/util/tmpfile.rb
rbbt-util-1.0.1 lib/rbbt/util/tmpfile.rb