Class: HTTPX::Response::Body

Inherits:
Object
  • Object
show all
Defined in:
lib/httpx/response.rb

Instance Method Summary collapse

Constructor Details

#initialize(response, threshold_size:, window_size: 1 << 14) ⇒ Body

Returns a new instance of Body.



86
87
88
89
90
91
92
93
94
95
# File 'lib/httpx/response.rb', line 86

def initialize(response, threshold_size:, window_size: 1 << 14)
  @response = response
  @headers = response.headers
  @threshold_size = threshold_size
  @window_size = window_size
  @encoding = response.content_type.charset || Encoding::BINARY
  @length = 0
  @buffer = nil
  @state = :idle
end

Instance Method Details

#==(other) ⇒ Object



174
175
176
# File 'lib/httpx/response.rb', line 174

def ==(other)
  to_s == other.to_s
end

#bytesizeObject



111
112
113
# File 'lib/httpx/response.rb', line 111

def bytesize
  @length
end

#closeObject

closes/cleans the buffer, resets everything



164
165
166
167
168
169
170
171
172
# File 'lib/httpx/response.rb', line 164

def close
  return if @state == :idle

  @buffer.close
  @buffer.unlink if @buffer.respond_to?(:unlink)
  @buffer = nil
  @length = 0
  @state = :idle
end

#copy_to(dest) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/httpx/response.rb', line 150

def copy_to(dest)
  return unless @buffer

  rewind

  if dest.respond_to?(:path) && @buffer.respond_to?(:path)
    FileUtils.mv(@buffer.path, dest.path)
  else
    @buffer.rewind
    ::IO.copy_stream(@buffer, dest)
  end
end

#eachObject



115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/httpx/response.rb', line 115

def each
  return enum_for(__method__) unless block_given?

  begin
    unless @state == :idle
      rewind
      while (chunk = @buffer.read(@window_size))
        yield(chunk.force_encoding(@encoding))
      end
    end
  ensure
    close
  end
end

#empty?Boolean

Returns:

  • (Boolean)


146
147
148
# File 'lib/httpx/response.rb', line 146

def empty?
  @length.zero?
end

#inspectObject

:nocov:



179
180
181
182
183
# File 'lib/httpx/response.rb', line 179

def inspect
  "#<HTTPX::Response::Body:#{object_id} " \
  "@state=#{@state} " \
  "@length=#{@length}>"
end

#read(*args) ⇒ Object



103
104
105
106
107
108
109
# File 'lib/httpx/response.rb', line 103

def read(*args)
  return unless @buffer

  rewind

  @buffer.read(*args)
end

#to_sObject Also known as: to_str



130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/httpx/response.rb', line 130

def to_s
  rewind
  if @buffer
    content = @buffer.read
    begin
      return content.force_encoding(@encoding)
    rescue ArgumentError # ex: unknown encoding name - utf
      return content
    end
  end
  "".b
ensure
  close
end

#write(chunk) ⇒ Object



97
98
99
100
101
# File 'lib/httpx/response.rb', line 97

def write(chunk)
  @length += chunk.bytesize
  transition
  @buffer.write(chunk)
end