Class: InstantRecord::Client::Transport::SseParser
- Inherits:
-
Object
- Object
- InstantRecord::Client::Transport::SseParser
- Defined in:
- lib/instant_record/client/transport.rb
Overview
Incremental parser for text/event-stream bodies. Pure Ruby so the sync loop is unit-testable without a browser. Yields one hash per event, with the SSE id merged in as "cursor".
Instance Method Summary collapse
- #feed(chunk) ⇒ Object
-
#initialize(&on_event) ⇒ SseParser
constructor
A new instance of SseParser.
Constructor Details
#initialize(&on_event) ⇒ SseParser
Returns a new instance of SseParser.
12 13 14 15 |
# File 'lib/instant_record/client/transport.rb', line 12 def initialize(&on_event) @buffer = +"" @on_event = on_event end |
Instance Method Details
#feed(chunk) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/instant_record/client/transport.rb', line 17 def feed(chunk) @buffer << chunk while (separator = @buffer.index("\n\n")) raw_event = @buffer.slice!(0, separator + 2) id = raw_event[/^id: (.+)$/, 1] data = raw_event[/^data: (.+)$/, 1] next unless data event = JSON.parse(data) event["cursor"] = id.to_i if id @on_event.call(event) end end |