Sha256: 1be8e28121e987bdcbd6ff5dda1192aa90411c5fa6785d6ed92c084c7b59ed25

Contents?: true

Size: 913 Bytes

Versions: 5

Compression:

Stored size: 913 Bytes

Contents

# frozen_string_literal: true

class ReadBackwardFile
  attr_reader :file,
              :chunk_size

  # Create a ReadBackwardFile
  #
  # @param [File] file
  #   the file to read backward from
  # @param [Integer] chunk_size
  #   the chunk size used to step through the file backwards
  #
  # @api public
  def initialize(file, chunk_size = 512)
    @file        = file
    @chunk_size  = chunk_size
    @file_size   = ::File.stat(file).size
  end

  # Read file in chunks
  #
  # @yield [String]
  #   the chunk from file content
  #
  # @api public
  def each_chunk
    file.seek(0, IO::SEEK_END)
    while file.tell > 0
      if file.tell < @chunk_size # don't read beyond file size
        @chunk_size = file.tell
      end
      file.seek(-@chunk_size, IO::SEEK_CUR)
      chunk = file.read(@chunk_size)
      yield(chunk)
      file.seek(-@chunk_size, IO::SEEK_CUR)
    end
  end
end # ReadBackwardFile

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
tty-file-0.10.0 lib/tty/file/read_backward_file.rb
tty-file-0.9.0 lib/tty/file/read_backward_file.rb
tty-file-0.8.0 lib/tty/file/read_backward_file.rb
tty-file-0.7.1 lib/tty/file/read_backward_file.rb
tty-file-0.7.0 lib/tty/file/read_backward_file.rb