Class: HTTPX::Response::Buffer

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

Overview

wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.

Instance Method Summary collapse

Constructor Details

#initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY) ⇒ Buffer

initializes buffer with the threshold_size over which the payload gets buffer to a tempfile, the initial bytesize, and the encoding.



12
13
14
15
16
17
18
# File 'lib/httpx/response/buffer.rb', line 12

def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
  @threshold_size = threshold_size
  @bytesize = bytesize
  @encoding = encoding
  @buffer = StringIO.new("".b)
  super(@buffer)
end

Instance Method Details

#closeObject

closes the buffer.



59
60
61
62
# File 'lib/httpx/response/buffer.rb', line 59

def close
  @buffer.close
  @buffer.unlink if @buffer.respond_to?(:unlink)
end

#initialize_dup(other) ⇒ Object



20
21
22
23
24
# File 'lib/httpx/response/buffer.rb', line 20

def initialize_dup(other)
  super

  @buffer = other.instance_variable_get(:@buffer).dup
end

#sizeObject

size in bytes of the buffered content.



27
28
29
# File 'lib/httpx/response/buffer.rb', line 27

def size
  @bytesize
end

#to_sObject

returns the buffered content as a string.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/httpx/response/buffer.rb', line 39

def to_s
  case @buffer
  when StringIO
    begin
      @buffer.string.force_encoding(@encoding)
    rescue ArgumentError
      @buffer.string
    end
  when Tempfile
    rewind
    content = _with_same_buffer_pos { @buffer.read }
    begin
      content.force_encoding(@encoding)
    rescue ArgumentError # ex: unknown encoding name - utf
      content
    end
  end
end

#write(chunk) ⇒ Object

writes the chunk into the buffer.



32
33
34
35
36
# File 'lib/httpx/response/buffer.rb', line 32

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