Module: TmpFile

Defined in:
lib/rbbt/util/tmpfile.rb

Constant Summary collapse

TMPDIR =
"/tmp/#{ENV['USER']}/tmpfiles"

Class Method Summary collapse

Class Method Details

.random_name(s = "tmp-", max = 1_000_000_000) ⇒ Object

Creates a random file name, with the given suffix and a random number up to max



20
21
22
23
# File 'lib/rbbt/util/tmpfile.rb', line 20

def self.random_name(s = "tmp-", max = 1_000_000_000)
  n = rand(max)
  s + n.to_s
end

.tmp_file(s = "tmp-", max = 1_000_000_000, dir = TMPDIR) ⇒ Object

Creates a random filename in the temporary directory



26
27
28
# File 'lib/rbbt/util/tmpfile.rb', line 26

def self.tmp_file(s = "tmp-", max=1_000_000_000, dir = TMPDIR)
  File.expand_path(File.join(dir, random_name(s, max)))
end

.tmpdirObject



13
14
15
# File 'lib/rbbt/util/tmpfile.rb', line 13

def self.tmpdir
  TMPDIR
end

.tmpdir=(tmpdir) ⇒ Object



8
9
10
11
# File 'lib/rbbt/util/tmpfile.rb', line 8

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

.with_dir(erase = true, options = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rbbt/util/tmpfile.rb', line 55

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

  FileUtils.mkdir_p tmpdir

  result = yield(tmpdir)

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

  result
end

.with_file(content = nil, erase = true, options = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rbbt/util/tmpfile.rb', line 30

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] || "tmp-"
  tmpdir = options[:tmpdir] || TMPDIR
  max = options[:max] || 1_000_000_000
  tmpfile = tmp_file prefix, max, tmpdir
  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