Class: Protocol::HTTP::Body::Streamable

Inherits:
Wrapper show all
Defined in:
lib/protocol/http/body/streamable.rb

Overview

Invokes a callback once the body has finished reading.

Instance Attribute Summary

Attributes inherited from Wrapper

#body

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Wrapper

#empty?, #inspect, #length

Methods inherited from Readable

#each, #empty?, #join, #length

Constructor Details

#initialize(body, callback, remaining = nil) ⇒ Streamable

Returns a new instance of Streamable.



42
43
44
45
46
47
# File 'lib/protocol/http/body/streamable.rb', line 42

def initialize(body, callback, remaining = nil)
  super(body)
  
  @callback = callback
  @remaining = remaining
end

Class Method Details

.wrap(message, &block) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/protocol/http/body/streamable.rb', line 30

def self.wrap(message, &block)
  if body = message&.body
    if remaining = body.length
      remaining = Integer(remaining)
    end
    
    message.body = self.new(message.body, block, remaining)
  else
    yield
  end
end

Instance Method Details

#close(error = nil) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/protocol/http/body/streamable.rb', line 61

def close(error = nil)
  if @body
    super
    
    @callback.call(error)
    
    @body = nil
  end
end

#finishObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/protocol/http/body/streamable.rb', line 49

def finish
  if @body
    result = super
    
    @callback.call
    
    @body = nil
    
    return result
  end
end

#readObject



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/protocol/http/body/streamable.rb', line 71

def read
  if chunk = super
    @remaining -= chunk.bytesize if @remaining
  else
    if @remaining and @remaining > 0
      raise EOFError, "Expected #{@remaining} more bytes!"
    end
  end
  
  return chunk
end