Class: FileReverseReader
- Inherits:
-
Object
- Object
- FileReverseReader
- Defined in:
- lib/file_reverse_reader.rb
Instance Attribute Summary collapse
-
#io ⇒ Object
readonly
Returns the value of attribute io.
-
#step ⇒ Object
readonly
Returns the value of attribute step.
Instance Method Summary collapse
- #binary_file? ⇒ Boolean
- #each_line(&block) ⇒ Object
-
#initialize(io, step = 1024 * 1024 * 1) ⇒ FileReverseReader
constructor
A new instance of FileReverseReader.
- #tail(limit = 10) ⇒ Object
Constructor Details
#initialize(io, step = 1024 * 1024 * 1) ⇒ FileReverseReader
Returns a new instance of FileReverseReader.
4 5 6 7 |
# File 'lib/file_reverse_reader.rb', line 4 def initialize(io, step = 1024 * 1024 * 1) @io = io @step = step end |
Instance Attribute Details
#io ⇒ Object (readonly)
Returns the value of attribute io.
2 3 4 |
# File 'lib/file_reverse_reader.rb', line 2 def io @io end |
#step ⇒ Object (readonly)
Returns the value of attribute step.
2 3 4 |
# File 'lib/file_reverse_reader.rb', line 2 def step @step end |
Instance Method Details
#binary_file? ⇒ Boolean
37 38 39 40 41 42 43 |
# File 'lib/file_reverse_reader.rb', line 37 def binary_file? sample = io.read(1024) || "" sample2 = sample.force_encoding('ascii-8bit').encode('us-ascii', :undef => :replace, :invalid => :replace, :replace => "") sample != sample2 # maybe binary file ensure io.rewind end |
#each_line(&block) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/file_reverse_reader.rb', line 9 def each_line(&block) io.seek(0, IO::SEEK_END) buf = "" loop do if reach_start_of_file? last_pos = io.pos io.seek(0, IO::SEEK_SET) buf.insert(0, io.read(last_pos)) split_each_line(buf, &block) break end io.seek(-1 * step, IO::SEEK_CUR) buf.insert(0, io.read(step)) io.seek(-1 * step, IO::SEEK_CUR) next if buf[$/].nil? gap = buf.index($/) buf.gsub!(/\A.*?\n/, "") split_each_line(buf, &block) buf = "" io.seek(gap, IO::SEEK_CUR) end end |
#tail(limit = 10) ⇒ Object
33 34 35 |
# File 'lib/file_reverse_reader.rb', line 33 def tail(limit = 10) enum_for(:each_line).first(limit).reverse end |