Module: TmpFile

Defined in:
lib/scout/tmpfile.rb

Class Method Summary collapse

Class Method Details

.in_dir(*args) ⇒ Object



85
86
87
88
89
90
91
# File 'lib/scout/tmpfile.rb', line 85

def self.in_dir(*args)
  with_dir(*args) do |dir|
    Misc.in_dir dir do
      yield dir
    end
  end
end

.random_name(prefix = 'tmp-', max = 1_000_000_000) ⇒ Object

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



23
24
25
26
# File 'lib/scout/tmpfile.rb', line 23

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

.tmp_file(prefix = 'tmp-', max = 1_000_000_000, dir = nil) ⇒ Object

Creates a random filename in the temporary directory



29
30
31
32
# File 'lib/scout/tmpfile.rb', line 29

def self.tmp_file(prefix = 'tmp-', max = 1_000_000_000, dir = nil)
  dir ||= TmpFile.tmpdir
  File.expand_path(File.join(dir, random_name(prefix, max)))
end

.tmpdirObject



17
18
19
# File 'lib/scout/tmpfile.rb', line 17

def self.tmpdir
  @tmpdir ||= self.user_tmp('tmpfiles')
end

.tmpdir=(tmpdir) ⇒ Object



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

def self.tmpdir=(tmpdir)
  @tmpdir = tmpdir
end

.user_tmp(subdir = nil) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/scout/tmpfile.rb', line 5

def self.user_tmp(subdir = nil)
  if subdir
    File.join(ENV["HOME"],"/tmp/scout", subdir)
  else
    File.join(ENV["HOME"],"/tmp/scout")
  end
end

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



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/scout/tmpfile.rb', line 72

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) && erase

  result
end

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



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/scout/tmpfile.rb', line 34

def self.with_file(content = nil, erase = true, options = {})
  if content.is_a?(Hash)
    options = content
    content = nil
    erase = true
  end
  if erase.is_a?(Hash)
    options = erase
    erase = true
  end

  prefix = options[:prefix] || 'tmp-'
  tmpdir = options[:tmpdir] || TmpFile.tmpdir
  max = options[:max] || 1_000_000_000
  tmpfile = tmp_file prefix, max, tmpdir
  tmpfile += ".#{options[:extension]}" if options[:extension]

  FileUtils.mkdir_p tmpdir
  if IO === content
    File.open(tmpfile, 'wb') do |f|
      begin
        while c = content.readpartial(1024)
          f << c
        end
      rescue EOFError
      end
    end
  elsif !content.nil?
    File.open(tmpfile, 'w') { |f| f.write content }
  end

  result = yield(tmpfile)

  FileUtils.rm_rf tmpfile if File.exist?(tmpfile) && erase

  result
end