Class: HTTP::FormData::CompositeIO

Inherits:
Object
  • Object
show all
Defined in:
lib/http/form_data/composite_io.rb

Overview

Provides IO interface across multiple IO objects.

Instance Method Summary collapse

Constructor Details

#initialize(ios) ⇒ CompositeIO

Creates a new CompositeIO from an array of IOs

Examples:

CompositeIO.new([StringIO.new("hello"), StringIO.new(" world")])

Parameters:

  • ios (Array<IO>)

    Array of IO objects



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/http/form_data/composite_io.rb', line 16

def initialize(ios)
  @index = 0
  @ios   = ios.map do |io|
    if io.is_a?(String)
      StringIO.new(io)
    elsif io.respond_to?(:read)
      io
    else
      raise ArgumentError,
            "#{io.inspect} is neither a String nor an IO object"
    end
  end
end

Instance Method Details

#read(length = nil, outbuf = nil) ⇒ String?

Reads and returns content across multiple IO objects

Examples:

composite_io.read     # => "hello world"
composite_io.read(5)  # => "hello"

Parameters:

  • length (Integer) (defaults to: nil)

    Number of bytes to retrieve

  • outbuf (String) (defaults to: nil)

    String to be replaced with retrieved data

Returns:

  • (String, nil)


40
41
42
43
44
45
46
47
# File 'lib/http/form_data/composite_io.rb', line 40

def read(length = nil, outbuf = nil)
  data   = outbuf.clear.force_encoding(Encoding::BINARY) if outbuf
  data ||= "".b

  read_chunks(length) { |chunk| data << chunk }

  data unless length && data.empty?
end

#rewindvoid

This method returns an undefined value.

Rewinds all IO objects and resets cursor

Examples:

composite_io.rewind


67
68
69
70
# File 'lib/http/form_data/composite_io.rb', line 67

def rewind
  @ios.each(&:rewind)
  @index = 0
end

#sizeInteger

Returns sum of all IO sizes

Examples:

composite_io.size # => 11

Returns:

  • (Integer)


56
57
58
# File 'lib/http/form_data/composite_io.rb', line 56

def size
  @size ||= @ios.sum(&:size)
end