Class: NetworkLoggerIO

Inherits:
IO
  • Object
show all
Defined in:
lib/network_logger_io.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ NetworkLoggerIO

Returns a new instance of NetworkLoggerIO.

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/network_logger_io.rb', line 6

def initialize(options)
  @options = options
  
  raise(ArgumentError, ':host is required') unless @options[:host]
  raise(ArgumentError, ':api_key is required') unless @options[:api_key]
  raise(ArgumentError, ':pid is required') unless @options[:pid]
  
  @options[:port] ||= 4455
  @options[:type] ||= 'default'
  @options[:buffer_size] ||= 512
  
  @socket = UDPSocket.new
  empty_buffer!
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/network_logger_io.rb', line 4

def options
  @options
end

Instance Method Details

#empty_buffer!Object



21
22
23
# File 'lib/network_logger_io.rb', line 21

def empty_buffer!
  @buffer = fresh_buffer
end

#flushObject



47
48
49
50
51
52
53
# File 'lib/network_logger_io.rb', line 47

def flush
  return self if @buffer == @api_key
  @buffer << "\0\0"
  @socket.send(@buffer, 0, @options[:host], @options[:port])
  empty_buffer!
  return self
end

#fresh_bufferObject



25
26
27
# File 'lib/network_logger_io.rb', line 25

def fresh_buffer
  [@options[:api_key].bytesize, @options[:api_key], @options[:type].bytesize, @options[:type], @options[:pid].bytesize, @options[:pid]].pack('nA*nA*nA*')
end

#write(data) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/network_logger_io.rb', line 29

def write(data)
  data.force_encoding('BINARY')
  data = data[0,@options[:buffer_size] - fresh_buffer.bytesize - 2]
  
  ## Pre-flush if the existing buffer plus the new data plus the terminator would be more than the buffer size
  if @buffer.bytesize + 2 + data.bytesize + 2 > @options[:buffer_size]
    self.flush
  end
  
  @buffer << [data.bytesize].pack('n')
  @buffer << data
  
  ## Flush is autoflush is set or the buffer is full
  self.flush if @options[:auto_flush] or @buffer.bytesize + 2 >= @options[:buffer_size]
  
  return data.bytesize
end