Class: LogfileInterval::Util::FileBackward

Inherits:
Object
  • Object
show all
Defined in:
lib/logfile_interval/util/file_backward.rb

Overview

Based on Perl’s File::ReadBackwards module, by Uri Guttman.

Constant Summary collapse

MAX_READ_SIZE =

1024

1 << 10

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ FileBackward

Returns a new instance of FileBackward.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/logfile_interval/util/file_backward.rb', line 7

def initialize( *args )
  return unless File.exist?(args[0])
  @file = File.new(*args)
  @file.seek(0, IO::SEEK_END)

  @current_pos = @file.pos

  @read_size = @file.pos % MAX_READ_SIZE
  @read_size = MAX_READ_SIZE if @read_size.zero?

  @line_buffer = Array.new
end

Instance Method Details

#closeObject



37
38
39
40
# File 'lib/logfile_interval/util/file_backward.rb', line 37

def close
  return unless @file
  @file.close()
end

#gets(sep_string = $/) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/logfile_interval/util/file_backward.rb', line 20

def gets( sep_string = $/ )
  return nil unless @file
  return @line_buffer.pop if @line_buffer.size > 2 or @current_pos.zero?

  @current_pos -= @read_size
  @file.seek(@current_pos, IO::SEEK_SET)

  @line_buffer[0] = "#{@file.read(@read_size)}#{@line_buffer[0]}"
  @read_size = MAX_READ_SIZE # Set a size for the next read.

  @line_buffer[0] =
  @line_buffer[0].scan(/.*?#{Regexp.escape(sep_string)}|.+/)
  @line_buffer.flatten!

  gets(sep_string)
end