Class: ReadBackwardFile

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/file/read_backward_file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, chunk_size = 512) ⇒ ReadBackwardFile

Create a ReadBackwardFile

Parameters:

  • file (File)

    the file to read backward from

  • chunk_size (Integer) (defaults to: 512)

    the chunk size used to step through the file backwards



15
16
17
18
19
# File 'lib/tty/file/read_backward_file.rb', line 15

def initialize(file, chunk_size = 512)
  @file        = file
  @chunk_size  = chunk_size
  @file_size   = ::File.stat(file).size
end

Instance Attribute Details

#chunk_sizeObject (readonly)

Returns the value of attribute chunk_size.



4
5
6
# File 'lib/tty/file/read_backward_file.rb', line 4

def chunk_size
  @chunk_size
end

#fileObject (readonly)

Returns the value of attribute file.



4
5
6
# File 'lib/tty/file/read_backward_file.rb', line 4

def file
  @file
end

Instance Method Details

#each_chunk {|String| ... } ⇒ Object

Read file in chunks

Yields:

  • (String)

    the chunk from file content



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/tty/file/read_backward_file.rb', line 27

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