Sha256: 4cc132b761580cf6a266b8d5d8b6d663c2d9af978ba2370fb83c9ff628592617

Contents?: true

Size: 1.13 KB

Versions: 267

Compression:

Stored size: 1.13 KB

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, options = {})
    tmpfile = tmp_file
    if options[:extension]
      tmpfile += ".#{options[:extension]}"
    end

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

    result = yield(tmpfile)

    FileUtils.rm_rf tmpfile if File.exists?(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.exists?(tmpdir) and erase

    result
  end
end

Version data entries

267 entries across 267 versions & 1 rubygems

Version Path
rbbt-util-5.17.52 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.51 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.50 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.49 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.48 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.47 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.46 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.45 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.44 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.43 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.42 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.41 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.40 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.39 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.38 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.37 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.35 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.33 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.32 lib/rbbt/util/tmpfile.rb
rbbt-util-5.17.31 lib/rbbt/util/tmpfile.rb