Module: Stud::Temporary

Defined in:
lib/stud/temporary.rb

Instance Method Summary collapse

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.



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/stud/temporary.rb', line 32

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

  if block_given?
    block.call(path)
    FileUtils.rm_r(path)
  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+”



20
21
22
23
# File 'lib/stud/temporary.rb', line 20

def file(prefix="", *args, &block)
  args << "w+" if args.empty?
  return File.new(pathname(prefix), *args)
end

#pathname(prefix = "") ⇒ Object

Returns a string for a randomly-generated temporary path.

This does not create any files.



9
10
11
12
# File 'lib/stud/temporary.rb', line 9

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