Module: Tins::TempIO

Included in:
Object, Enum
Defined in:
lib/tins/temp_io.rb,
lib/tins/temp_io_enum.rb

Overview

A module for creating temporary files and handling their contents securely.

Defined Under Namespace

Classes: Enum

Instance Method Summary collapse

Instance Method Details

#temp_io(content: nil, name: __method__) {|io| ... } ⇒ Object

Creates a temporary file with the given content and yields it to a block.

Parameters:

  • content (String, #call) (defaults to: nil)

    the content to write to the temporary file

  • name (String, Symbol) (defaults to: __method__)

    the base name for the temporary file

Yields:

  • (io)

    yields the temporary file handle to the given block

Returns:

  • (Object)

    the return value of the block



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/tins/temp_io.rb', line 12

def temp_io(content: nil, name: __method__)
  content.nil? and raise ArgumentError, "missing keyword: content"
  name = File.basename(name.to_s)
  Dir.mktmpdir do |dir|
    name = File.join(dir, name)
    File.open(name, 'w+b') do |io|
      if content.respond_to?(:call)
        if content.respond_to?(:arity) && content.arity == 1
          content.call(io)
        else
          io.write content.call
        end
      else
        io.write content
      end
      io.rewind
      yield io
    end
  end
end