class SSE::Impl::EventParser

Accepts lines of text via an enumerator, and parses them into SSE messages. You will not need to use this directly if you are using {Client}, but it may be useful for testing.

Public Class Methods

new(lines) click to toggle source

Constructs an instance of EventParser.

@param [Enumerator] lines an enumerator that will yield one line of text at a time

# File lib/ld-eventsource/impl/event_parser.rb, line 25
def initialize(lines)
  @lines = lines
  reset_buffers
end

Public Instance Methods

items() click to toggle source

Generator that parses the input iterator and returns instances of {StreamEvent} or {SetRetryInterval}.

# File lib/ld-eventsource/impl/event_parser.rb, line 31
def items
  Enumerator.new do |gen|
    @lines.each do |line|
      line.chomp!
      if line.empty?
        event = maybe_create_event
        reset_buffers
        gen.yield event if !event.nil?
      else
        case line
          when /^(\w+): ?(.*)$/
            item = process_field($1, $2)
            gen.yield item if !item.nil?
        end
      end
    end
  end
end

Private Instance Methods

maybe_create_event() click to toggle source
# File lib/ld-eventsource/impl/event_parser.rb, line 75
def maybe_create_event
  return nil if @data.empty?
  StreamEvent.new(@type || :message, @data, @id)
end
process_field(name, value) click to toggle source
# File lib/ld-eventsource/impl/event_parser.rb, line 58
def process_field(name, value)
  case name
    when "event"
      @type = value.to_sym
    when "data"
      @data << "\n" if !@data.empty?
      @data << value
    when "id"
      @id = value
    when "retry"
      if /^(?<num>\d+)$/ =~ value
        return SetRetryInterval.new(num.to_i)
      end
  end
  nil
end
reset_buffers() click to toggle source
# File lib/ld-eventsource/impl/event_parser.rb, line 52
def reset_buffers
  @id = nil
  @type = nil
  @data = ""
end