class File
Public Class Methods
tail(path, n = 1)
click to toggle source
@param path [String] - the path to the file @param n [Integer] - the number of lines to read from the path @summary Reads N lines from the end of file, without reading the entire file into memory @return [String] - the data read from the file
# 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