Class: Log::FileReader

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/log/filereader.rb

Defined Under Namespace

Classes: Filter

Instance Method Summary collapse

Methods included from Enumerable

#join

Constructor Details

#initialize(file) ⇒ FileReader

Returns a new instance of FileReader.



32
33
34
35
36
37
# File 'lib/log/filereader.rb', line 32

def initialize(file)
  @file    = ::File.open(file, "r")
  @pos     = 0
  @cache   = {}
  @filters = []
end

Instance Method Details

#add_filter(type, *args) ⇒ Object



39
40
41
# File 'lib/log/filereader.rb', line 39

def add_filter(type, *args)
  @filters << Filter.new(type, *args)
end

#eachObject



74
75
76
77
78
79
# File 'lib/log/filereader.rb', line 74

def each
  while line = @file.gets
    entry = Log::Entry.deserialize(line)
    yield(entry) if matches(entry)
  end
end

#head(n) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/log/filereader.rb', line 47

def head(n)
  i = 0
  while line = @file.gets and i < n
    entry = Log::Entry.deserialize(line)
    if matches(entry) then
      yield(entry)
      i+=1
    end
  end
  entries
end

#matches(entry) ⇒ Object



43
44
45
# File 'lib/log/filereader.rb', line 43

def matches(entry)
  @filters.all? { |filter| filter =~ entry }
end

#tail(n, &block) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/log/filereader.rb', line 59

def tail(n, &block)
  entries = []
  while line = @file.gets and entries.length < n
    entry = Log::Entry.deserialize(line)
    entries.push entry if matches(entry)
  end
  while line = @file.gets
    entry = Log::Entry.deserialize(line)
    entries.push entry if matches(entry)
    entries.shift
  end
  entries.compact
  entries.each(&block)
end