Class: PowerTrack::DataBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/powertrack/streaming/data_buffer.rb

Overview

A buffer of data received from PowerTrack. Useful for managing the sequential chunk of bytes sent of the stream by GNIP and slice them into well-formatted messages.

Constant Summary collapse

MESSAGE_PATTERN =

The pattern used by GNIP PowerTrack to delimitate a single message.

/^([^\r]*)\r\n/m.freeze

Instance Method Summary collapse

Constructor Details

#initializeDataBuffer

Builds a new data buffer.



11
12
13
# File 'lib/powertrack/streaming/data_buffer.rb', line 11

def initialize
  @buffer = ''
end

Instance Method Details

#process(chunk, &block) ⇒ Object

Add a chunk of bytes to the buffer and pass the new message(s) extracted to the block provided.



17
18
19
20
21
22
23
24
# File 'lib/powertrack/streaming/data_buffer.rb', line 17

def process(chunk, &block)
  @buffer.concat(chunk)
  @buffer.gsub!(MESSAGE_PATTERN) do |match|
    yield($1.to_s) if block_given?
    # erase the message
    ''
  end
end

#reset!Object

Resets the buffer, therefore losing any bytes received from PowerTrack.



32
33
34
# File 'lib/powertrack/streaming/data_buffer.rb', line 32

def reset!
  @buffer = ''
end

#sizeObject

The current size of the buffer.



27
28
29
# File 'lib/powertrack/streaming/data_buffer.rb', line 27

def size
  @buffer.size
end