Class: Rack::TrafficLogger::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/traffic_logger/reader.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, output, **options) ⇒ Reader

Returns a new instance of Reader.



11
12
13
14
15
16
17
# File 'lib/rack/traffic_logger/reader.rb', line 11

def initialize(input, output, **options)
  @input = input
  @output = output
  @formatter = Formatter::Stream.new(**options)
  Signal.trap('INT') { done }
  readline until @done
end

Class Method Details

.start(input, output, **options) ⇒ Object



7
8
9
# File 'lib/rack/traffic_logger/reader.rb', line 7

def self.start(input, output, **options)
  new input, output, **options
end

Instance Method Details

#doneObject



43
44
45
# File 'lib/rack/traffic_logger/reader.rb', line 43

def done
  @done = true
end

#readlineObject

Reads a line from input, formats it, and sends it to output



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rack/traffic_logger/reader.rb', line 20

def readline
  buffer = ''
  loop do
    begin
      buffer << @input.read_nonblock(1)
      return writeline buffer if buffer[-1] == "\n"
    rescue IO::EAGAINWaitReadable
      sleep 0.1
    rescue EOFError
      return done
    end
  end
end

#writeline(line) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/rack/traffic_logger/reader.rb', line 34

def writeline(line)
  begin
    hash = JSON.parse(line)
    @output << @formatter.format(hash)
  rescue
    @output << line
  end
end