forked from httprb/http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbody.rb
64 lines (54 loc) · 1.54 KB
/
body.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
require "forwardable"
require "http/client"
module HTTP
class Response
# A streamable response body, also easily converted into a string
class Body
extend Forwardable
include Enumerable
def_delegator :to_s, :empty?
def initialize(client)
@client = client
@streaming = nil
@contents = nil
end
# (see HTTP::Client#readpartial)
def readpartial(*args)
stream!
@client.readpartial(*args)
end
# Iterate over the body, allowing it to be enumerable
def each
while (chunk = readpartial)
yield chunk
end
end
# @return [String] eagerly consume the entire body as a string
def to_s
return @contents if @contents
fail StateError, "body is being streamed" unless @streaming.nil?
begin
@streaming = false
@contents = "".force_encoding(Encoding::UTF_8)
while (chunk = @client.readpartial)
@contents << chunk.force_encoding(Encoding::ASCII_8BIT)
end
rescue
@contents = nil
raise
end
@contents
end
alias_method :to_str, :to_s
# Assert that the body is actively being streamed
def stream!
fail StateError, "body has already been consumed" if @streaming == false
@streaming = true
end
# Easier to interpret string inspect
def inspect
"#<#{self.class}:#{object_id.to_s(16)} @streaming=#{!!@streaming}>"
end
end
end
end