Module: Scarpe::Components::FileHelpers

Included in:
ProcessHelpers, SegmentedFileLoader, Test::Helpers
Defined in:
scarpe-components/lib/scarpe/components/file_helpers.rb

Instance Method Summary collapse

Instance Method Details

#with_tempfile(prefix, contents, dir: Dir.tmpdir) {|the| ... } ⇒ Object

Create a temporary file with the given prefix and contents. Execute the block of code with it in place. Make sure it gets cleaned up afterward.

Parameters:

  • prefix (String)

    the prefix passed to Tempfile to identify this file on disk

  • contents (String)

    the file contents that should be written to Tempfile

  • dir (String) (defaults to: Dir.tmpdir)

    the directory to create the tempfile in

Yields:

  • The code to execute with the tempfile present

Yield Parameters:

  • the

    path of the new tempfile



18
19
20
21
22
23
24
25
26
27
# File 'scarpe-components/lib/scarpe/components/file_helpers.rb', line 18

def with_tempfile(prefix, contents, dir: Dir.tmpdir)
  t = Tempfile.new(prefix, dir)
  t.write(contents)
  t.flush # Make sure the contents are written out

  yield(t.path)
ensure
  t.close
  t.unlink
end

#with_tempfiles(tf_specs) {|An| ... } ⇒ Object

Create multiple tempfiles, with given contents, in given directories, and execute the block in that context. When the block is finished, make sure all tempfiles are deleted.

Pass an array of arrays, where each array is of the form: [prefix, contents, (optional)dir]

I don't love inlining with_tempfile's contents into here. But calling it iteratively or recursively was difficult when I tried it the obvious ways.

This method should be equivalent to calling with_tempfile once for each entry in the array, in a set of nested blocks.

Parameters:

  • tf_specs (Array<Array>)

    The array of tempfile prefixes, contents and directories

Yields:

  • The code to execute with those tempfiles present

Yield Parameters:

  • An

    array of paths to tempfiles, in the same order as tf_specs



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'scarpe-components/lib/scarpe/components/file_helpers.rb', line 48

def with_tempfiles(tf_specs, &block)
  tempfiles = []
  tf_specs.each do |prefix, contents, dir|
    dir ||= Dir.tmpdir
    t = Tempfile.new(prefix, dir)
    tempfiles << t
    t.write(contents)
    t.flush # Make sure the contents are written out
  end

  args = tempfiles.map(&:path)
  yield(args)
ensure
  tempfiles.each do |t|
    t.close
    t.unlink
  end
end