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.



78
79
80
81
82
83
84
85
86
87
# File 'lib/httpx/response.rb', line 78

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



158
159
160
# File 'lib/httpx/response.rb', line 158

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

#bytesizeObject



100
101
102
# File 'lib/httpx/response.rb', line 100

def bytesize
  @length
end

#closeObject

closes/cleans the buffer, resets everything



149
150
151
152
153
154
155
156
# File 'lib/httpx/response.rb', line 149

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



138
139
140
141
142
143
144
145
146
# File 'lib/httpx/response.rb', line 138

def copy_to(dest)
  return unless @buffer
  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



104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/httpx/response.rb', line 104

def each
  return enum_for(__method__) unless block_given?
  begin
    unless @state == :idle
      rewind
      while (chunk = @buffer.read(@window_size))
        yield(chunk)
      end
    end
  ensure
    close
  end
end

#empty?Boolean

Returns:

  • (Boolean)


134
135
136
# File 'lib/httpx/response.rb', line 134

def empty?
  @length.zero?
end

#read(*args) ⇒ Object



95
96
97
98
# File 'lib/httpx/response.rb', line 95

def read(*args)
  return unless @buffer
  @buffer.read(*args)
end

#to_sObject Also known as: to_str



118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/httpx/response.rb', line 118

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
  ""
ensure
  close
end

#write(chunk) ⇒ Object



89
90
91
92
93
# File 'lib/httpx/response.rb', line 89

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