Module: Stud::Temporary

Includes:
With
Defined in:
lib/stud/temporary.rb

Instance Method Summary collapse

Methods included from With

#with

Instance Method Details

#directory(prefix = "", &block) ⇒ Object

Make a temporary directory.

If given a block, the directory path is given to the block. WHen the block finishes, the directory and all its contents will be deleted.

If no block given, it will return the path to a newly created directory. You are responsible for then cleaning up.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/stud/temporary.rb', line 46

def directory(prefix="", &block)
  path = pathname(prefix)
  Dir.mkdir(path)

  if block_given?
    begin
      block.call(path)
    ensure
      FileUtils.rm_r(path)
    end
  else
    return path
  end
end

#file(prefix = "", *args, &block) ⇒ Object

Return a File handle to a randomly-generated path.

Any arguments beyond the first (prefix) argument will be given to File.new.

If no file args are given, the default file mode is “w+”



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/stud/temporary.rb', line 23

def file(prefix="", *args, &block)
  args << "w+" if args.empty?
  if block_given?
    with(File.new(pathname(prefix), *args)) do |fd|
      begin
        block.call(fd)
        fd.close
      ensure
        File.unlink(fd.path)
      end
    end
  else
    return File.new(pathname(prefix), *args)
  end
end

#pathname(prefix = "") ⇒ Object

Returns a string for a randomly-generated temporary path.

This does not create any files.



12
13
14
15
# File 'lib/stud/temporary.rb', line 12

def pathname(prefix="")
  root = ENV["TMP"] || ENV["TMPDIR"] || ENV["TEMP"] || "/tmp"
  return File.join(root, "#{prefix}-#{SecureRandom.uuid}")
end