Class: Logpos

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

Defined Under Namespace

Classes: TripleArray

Constant Summary collapse

VERSION =
'1.0.2'
TIME_PARSER_CLASS =
if defined? Chronic
  Chronic
else
  require 'active_support'
  Time
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLogpos

Returns a new instance of Logpos.



14
15
16
# File 'lib/logpos.rb', line 14

def initialize
  @time_parser = proc {|line| line.match(/^Started/) && TIME_PARSER_CLASS.parse(line.split(/for [0-9\.]* at /)[-1]) }
end

Instance Attribute Details

#time_parserObject

Returns the value of attribute time_parser.



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

def time_parser
  @time_parser
end

Class Method Details

.seek_pos_before(file_path, lastest_visited_at) ⇒ Object



18
19
20
# File 'lib/logpos.rb', line 18

def self.seek_pos_before file_path, lastest_visited_at
  Logpos.new.seek_pos_before file_path, lastest_visited_at
end

Instance Method Details

#seek_pos_before(file_path, lastest_visited_at) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/logpos.rb', line 22

def seek_pos_before file_path, lastest_visited_at
  ta = TripleArray.new lastest_visited_at

  @file ||= File.open(file_path)
  @file.reopen(file_path)
  pos_start, pos_end = 0, File.size(@file)
  pos_mid = pos_end / 2
  time = Time.at(0)
  between = -1.0/0

  loop do
    pos_mid, time = seek_log_pos(@file, pos_mid)
    break if time.nil? || (pos_mid == pos_end)

    time_valid = lastest_visited_at >= time
    break if time_valid && ((lastest_visited_at - time) >= between.abs)
    between = lastest_visited_at - time
    break if time_valid && ta.push(pos_mid, time).nil?

    if between > 0
      pos_start = pos_mid
      pos_mid = (pos_mid + pos_end) / 2
    elsif between < 0
      pos_end = pos_mid
      pos_mid = (pos_mid + pos_start) / 2
    end
  end
  @file.close

  return ta.oldest.pos
end