Class: LogSlice

Inherits:
Object
  • Object
show all
Defined in:
lib/log_slice.rb,
lib/log_slice/search_boundary.rb

Defined Under Namespace

Classes: SearchBoundary

Constant Summary collapse

NEWLINE =
"\n"
NEWLINE_CHAR =
"\n"[0]

Instance Method Summary collapse

Constructor Details

#initialize(log_file, options = {}) ⇒ LogSlice

Returns a new instance of LogSlice.

Parameters:

  • log_file (File, String)
  • options (Hash) (defaults to: {})

    :exact_match default false



10
11
12
13
14
15
# File 'lib/log_slice.rb', line 10

def initialize log_file, options={}
  @file = log_file.respond_to?(:seek) ? log_file : File.open(log_file, 'r')
  @exact_match = options[:exact_match] || false
  @search_boundary = SearchBoundary.new(@file.stat.size)
  @line_cursor = nil
end

Instance Method Details

#find(&compare) ⇒ File?

Find line in the file using the comparison function. Depends on lines being sorted. The comparison function will be passed lines from the file. It must return -1 if the line is later than the one it’s looking for, 1 if the line is earlier than the one it’s looking for, and 0 if it is the line it’s looking for.

Parameters:

  • compare (Proc)

    comparison function

Returns:

  • (File, nil)

    file after seeking to start of line or nil if line not found



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

def find &compare
  reset_progress_check
  @search_boundary.reset
  line = find_next_newline
  while making_progress?
    comp_value = compare.call(line)
    if comp_value == 0 # found matching line
      backtrack_to_first_line_match compare
      return @file
    else
      @search_boundary.send(comp_value < 0 ? :cursor_back : :cursor_forward)
      line = find_next_newline
    end
  end
  if @exact_match
    nil
  else
    backtrack_to_gap compare
    return @file.eof? ? nil : @file
  end
end