Module: TmpFile
- Defined in:
- lib/rbbt/util/tmpfile.rb
Constant Summary collapse
- TMPDIR =
"/tmp/#{ENV['USER']}/tmpfiles"
Class Method Summary collapse
-
.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
. -
.tmp_file(s = "tmp-", max = 1_000_000_000, dir = TMPDIR) ⇒ Object
Creates a random filename in the temporary directory.
- .tmpdir ⇒ Object
- .tmpdir=(tmpdir) ⇒ Object
- .with_dir(erase = true, options = {}) ⇒ Object
- .with_file(content = nil, erase = true, options = {}) ⇒ Object
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.(File.join(dir, random_name(s, max))) end |
.tmpdir ⇒ Object
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, = {}) prefix = [: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, = {}) , content, erase = content, nil, true if Hash === content , erase = erase, true if Hash === erase prefix = [:prefix] || "tmp-" tmpdir = [:tmpdir] || TMPDIR max = [:max] || 1_000_000_000 tmpfile = tmp_file prefix, max, tmpdir if [:extension] tmpfile += ".#{[: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 |