Module: Scarpe::Components::FileHelpers
- Included in:
- ProcessHelpers, SegmentedFileLoader, Test::Helpers
- Defined in:
- lib/scarpe/components/file_helpers.rb
Instance Method Summary collapse
-
#with_tempfile(prefix, contents, dir: Dir.tmpdir) {|the| ... } ⇒ Object
Create a temporary file with the given prefix and contents.
-
#with_tempfiles(tf_specs) {|An| ... } ⇒ Object
Create multiple tempfiles, with given contents, in given directories, and execute the block in that context.
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.
18 19 20 21 22 23 24 25 26 27 |
# File '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.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File '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 |