Class: Kronk::MultipartIO

Inherits:
Object
  • Object
show all
Defined in:
lib/kronk/multipart_io.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*parts) ⇒ MultipartIO

Returns a new instance of MultipartIO.



7
8
9
10
11
12
13
14
# File 'lib/kronk/multipart_io.rb', line 7

def initialize *parts
  @parts     = []
  @curr_part = 0

  parts.each do |part|
    add part
  end
end

Instance Attribute Details

#curr_partObject (readonly)

Returns the value of attribute curr_part.



5
6
7
# File 'lib/kronk/multipart_io.rb', line 5

def curr_part
  @curr_part
end

#partsObject (readonly)

Returns the value of attribute parts.



5
6
7
# File 'lib/kronk/multipart_io.rb', line 5

def parts
  @parts
end

Instance Method Details

#add(part) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/kronk/multipart_io.rb', line 17

def add part
  if String === part
    @parts << StringIO.new(part)

  elsif part.respond_to?(:read)
    @parts << part

  else
    raise ArgumentError, "Invalid part #{part.inspect}"
  end

  @curr_part ||= @parts.length - 1
  @parts.last
end

#closeObject



33
34
35
36
# File 'lib/kronk/multipart_io.rb', line 33

def close
  @parts.each(&:close)
  nil
end

#eof?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/kronk/multipart_io.rb', line 72

def eof?
  @curr_part.nil?
end

#read(bytes = nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/kronk/multipart_io.rb', line 39

def read bytes=nil
  return read_all if bytes.nil?
  return if @parts.empty? || eof?

  buff = ""

  until @curr_part.nil?
    bytes = bytes - buff.bytes.count
    buff << @parts[@curr_part].read(bytes).to_s
    break if buff.bytes.count >= bytes

    @curr_part += 1
    @curr_part = nil if @curr_part >= @parts.length
  end

  return if buff.empty?
  buff
end

#read_allObject



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/kronk/multipart_io.rb', line 59

def read_all
  return "" if eof?

  out = @parts[@curr_part..-1].inject("") do |out, curr|
    @curr_part += 1
    out << curr.read
  end

  @curr_part = nil
  out
end

#sizeObject



77
78
79
80
81
82
83
84
85
86
# File 'lib/kronk/multipart_io.rb', line 77

def size
  total = 0

  @parts.each do |part|
    return nil unless part.respond_to?(:size) && part.size
    total += part.size
  end

  total
end