Class: Trainspotter::Ingest::Reader

Inherits:
Object
  • Object
show all
Defined in:
app/jobs/trainspotter/ingest/reader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = nil) ⇒ Reader

Returns a new instance of Reader.



6
7
8
9
10
11
# File 'app/jobs/trainspotter/ingest/reader.rb', line 6

def initialize(filename = nil)
  @filename = filename || Trainspotter.default_log_file
  @path = File.join(Trainspotter.log_directory, @filename)
  @parser = Parser.new
  @file_position = 0
end

Instance Attribute Details

#parserObject (readonly)

Returns the value of attribute parser.



4
5
6
# File 'app/jobs/trainspotter/ingest/reader.rb', line 4

def parser
  @parser
end

#pathObject (readonly)

Returns the value of attribute path.



4
5
6
# File 'app/jobs/trainspotter/ingest/reader.rb', line 4

def path
  @path
end

Instance Method Details

#poll_for_changesObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/jobs/trainspotter/ingest/reader.rb', line 42

def poll_for_changes
  new_lines = read_new_lines
  return [] if new_lines.empty?

  new_groups = []
  new_lines.each do |line|
    parser.parse_line(line)
    if parser.groups.any? && parser.groups.last.completed?
      new_groups << parser.groups.last
    end
  end

  new_groups
end

#read_new_linesObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'app/jobs/trainspotter/ingest/reader.rb', line 21

def read_new_lines
  return [] unless File.exist?(path)

  current_size = File.size(path)

  if current_size < @file_position
    @file_position = 0
  end

  return [] if current_size == @file_position

  new_lines = []
  File.open(path, "r") do |file|
    file.seek(@file_position)
    new_lines = file.readlines
    @file_position = file.pos
  end

  new_lines
end

#read_recent(limit: 100) ⇒ Object



13
14
15
16
17
18
19
# File 'app/jobs/trainspotter/ingest/reader.rb', line 13

def read_recent(limit: 100)
  return [] unless File.exist?(path)

  lines = tail_lines(limit * 20)
  groups = parser.parse_lines(lines)
  groups.last(limit)
end