Class: MstdnIvory::Parser

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

Overview

This class parse stream data.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Parser

Returns a new instance of Parser.



7
8
9
10
11
# File 'lib/mstdn_ivory/parser.rb', line 7

def initialize(&block)
  @parser = HTTP::Parser.new(self)
  @buffer = {}
  @block = block
end

Instance Method Details

#<<(body) ⇒ Object



13
14
15
# File 'lib/mstdn_ivory/parser.rb', line 13

def <<(body)
  @parser << body
end

#on_body(data) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mstdn_ivory/parser.rb', line 17

def on_body(data)
  if (match_data = data.match(/event: ([a-z]+)/))
    @buffer[:type] = match_data[1].to_sym
  elsif (match_data = data.match(/data: (.+)/m))
    @buffer[:data] = Oj.load(match_data[1])

    if @buffer[:type]
      @block.call(@buffer[:type], @buffer[:data])
    else
      @buffer = {}
    end
  end
end