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

Returns a new instance of CompositeIO.

Parameters:

  • ios (Array<IO>)

    Array of IO objects



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/http/form_data/composite_io.rb', line 10

def initialize(ios)
  @index  = 0
  @buffer = "".b
  @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 partial content acrosss multiple IO objects.

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)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/http/form_data/composite_io.rb', line 31

def read(length = nil, outbuf = nil)
  outbuf = outbuf.to_s.clear
  # buffer in JRuby is sometimes US-ASCII, force to ASCII-8BIT
  outbuf.force_encoding(Encoding::BINARY)

  while current_io
    current_io.read(length, @buffer)
    outbuf << @buffer.force_encoding(Encoding::BINARY)

    if length
      length -= @buffer.bytesize
      break if length.zero?
    end

    advance_io
  end

  outbuf unless length && outbuf.empty?
end

#rewindObject

Rewinds all IO objects and set cursor to the first IO object.



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

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

#sizeObject

Returns sum of all IO sizes.



52
53
54
# File 'lib/http/form_data/composite_io.rb', line 52

def size
  @size ||= @ios.map(&:size).inject(0, :+)
end