Class: X::StreamParser

Inherits:
Object
  • Object
show all
Defined in:
lib/x/stream_parser.rb

Overview

Handles streaming responses from the X API

Constant Summary collapse

LINE_DELIMITER =

Line delimiter for streaming responses

"\r\n".freeze

Instance Method Summary collapse

Instance Method Details

#process(response:, response_parser:, array_class: nil, object_class: nil) {|Hash, Array| ... } ⇒ void

This method returns an undefined value.

Process a streaming response and yield parsed JSON objects

Examples:

Process a streaming response

handler.process(response: response, response_parser: parser) { |json| puts json }

Parameters:

  • response (Net::HTTPResponse)

    the HTTP response to stream

  • response_parser (ResponseParser)

    the response parser for error handling

  • array_class (Class, nil) (defaults to: nil)

    the class for parsing JSON arrays

  • object_class (Class, nil) (defaults to: nil)

    the class for parsing JSON objects

Yields:

  • (Hash, Array)

    each parsed JSON object from the stream

Raises:

  • (HTTPError)

    if the response is not successful



24
25
26
27
28
29
30
31
32
33
# File 'lib/x/stream_parser.rb', line 24

def process(response:, response_parser:, array_class: nil, object_class: nil, &block)
  response_parser.parse(response:) unless response.is_a?(Net::HTTPSuccess)

  buffer = +""
  response.read_body do |chunk|
    buffer << chunk
    process_buffer(buffer:, array_class:, object_class:, &block)
  end
  process_remaining(buffer:, array_class:, object_class:, &block)
end