@@ -20,14 +20,15 @@ def initialize(stream, length: nil, encoding: Encoding::BINARY)
20
20
@connection = stream . is_a? ( Inflater ) ? stream . connection : stream
21
21
@streaming = nil
22
22
@contents = nil
23
- @encoding = encoding
23
+ @encoding = find_encoding ( encoding )
24
24
@length = length || Float ::INFINITY
25
25
end
26
26
27
27
# (see HTTP::Client#readpartial)
28
28
def readpartial ( *args )
29
29
stream!
30
- @stream . readpartial ( *args )
30
+ chunk = @stream . readpartial ( *args )
31
+ chunk . force_encoding ( @encoding ) if chunk
31
32
end
32
33
33
34
# Iterate over the body, allowing it to be enumerable
@@ -43,22 +44,15 @@ def to_s
43
44
44
45
raise StateError , "body is being streamed" unless @streaming . nil?
45
46
46
- # see issue 312
47
- begin
48
- encoding = Encoding . find @encoding
49
- rescue ArgumentError
50
- encoding = Encoding ::BINARY
51
- end
52
-
53
47
begin
54
48
@streaming = false
55
- @contents = String . new ( "" ) . force_encoding ( encoding )
49
+ @contents = String . new ( "" ) . force_encoding ( @ encoding)
56
50
57
51
length = @length
58
52
59
53
while length > 0 && ( chunk = @stream . readpartial )
60
54
length -= chunk . bytesize
61
- @contents << chunk . force_encoding ( encoding )
55
+ @contents << chunk . force_encoding ( @ encoding)
62
56
end
63
57
rescue
64
58
@contents = nil
@@ -79,6 +73,15 @@ def stream!
79
73
def inspect
80
74
"#<#{ self . class } :#{ object_id . to_s ( 16 ) } @streaming=#{ !!@streaming } >"
81
75
end
76
+
77
+ private
78
+
79
+ # Retrieve encoding by name. If encoding cannot be found, default to binary.
80
+ def find_encoding ( encoding )
81
+ Encoding . find encoding
82
+ rescue ArgumentError
83
+ Encoding ::BINARY
84
+ end
82
85
end
83
86
end
84
87
end
0 commit comments