Class: File

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

Class Method Summary collapse

Class Method Details

.tail(path, n = 1) ⇒ String

Returns - the data read from the file.

Parameters:

  • path (String)
    • the path to the file

  • n (Integer) (defaults to: 1)
    • the number of lines to read from the path

Returns:

  • (String)
    • the data read from the file



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/compute_unit/monkey_patches.rb', line 8

def self.tail(path, n = 1)
  return '' unless File.exist?(path)

  File.open(path, 'r') do |file|
    buffer_s = 512
    line_count = 0
    file.seek(0, IO::SEEK_END)

    offset = file.pos # we start at the end

    while line_count <= n && offset > 0
      to_read = if (offset - buffer_s) < 0
                  offset
                else
                  buffer_s
                end

      file.seek(offset - to_read)
      data = file.read(to_read)

      data.reverse.each_char do |c|
        if line_count > n
          offset += 1
          break
        end
        offset -= 1
        line_count += 1 if c == "\n"
      end
    end
    file.seek(offset)
    file.read
  end
end