Class: ServerSentEvents::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/server_sent_events/parser.rb

Overview

Instances of this class can be used to parse incoming data into Events. This class is most commonly used by the Client to convert data from the server into series of events.

This parser strictly follows the parsing and interpreting parts of the html spec.

To use the parser, simply create new instance and feed it data using #push method:

parser = Parser.new
loop do
  parser.push(get_data_from_somewhere).each do |event|
    do_something_with(event)
  end
end

Constant Summary collapse

LINE_DELIMITER =
/\r\n|\r|\n/

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



27
28
29
30
# File 'lib/server_sent_events/parser.rb', line 27

def initialize
  @buffer = ""
  @event = Event.new
end

Instance Method Details

#push(data) ⇒ Array<Event>

Add new data to parser.

Newly pushed data is added to any remaining data from previous calls, which is then checked for any complete events that are returned.

Note that push can generate zero, one or more events, depending on data from previous runs and currently passed-in data. After the call returns, all complete events are returned (internal buffer contains only incomplete event or is empty).

Returns:

  • (Array<Event>)

    complete events



43
44
45
46
# File 'lib/server_sent_events/parser.rb', line 43

def push(data)
  @buffer += data
  process_buffer
end