Class: Teletype::Paginator
- Inherits:
-
Object
- Object
- Teletype::Paginator
- Defined in:
- lib/teletype/paginator.rb
Overview
Pager divides lines of text into proper screen size and provides page suggestion based on statistics of click accuracy.
Instance Method Summary collapse
-
#initialize(profile, text, suggest:, screen:, stats:) ⇒ Paginator
constructor
A new instance of Paginator.
- #pick(suggestions) ⇒ Object
- #run ⇒ Object
- #save ⇒ Object
- #split(text, length) ⇒ Object
Constructor Details
#initialize(profile, text, suggest:, screen:, stats:) ⇒ Paginator
Returns a new instance of Paginator.
9 10 11 12 13 14 15 16 17 18 |
# File 'lib/teletype/paginator.rb', line 9 def initialize(profile, text, suggest:, screen:, stats:) @screen = screen @stats = stats @suggest = suggest @lines = split(text, @screen.width) @linenum = 0 @pagefile = File.join(profile, "page-#{Digest::MD5.hexdigest(text)}") end |
Instance Method Details
#pick(suggestions) ⇒ Object
41 42 43 44 45 |
# File 'lib/teletype/paginator.rb', line 41 def pick(suggestions) index = 0.0 # preserve the original order matches = ->(line) { suggestions.map { |keys| line.scan(keys).count }.sum - (index += 0.0001) } @lines.sort_by { |line| matches.call(line) }.last(@suggest) end |
#run ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/teletype/paginator.rb', line 24 def run prev = File.exist?(@pagefile) ? Integer(File.read(@pagefile).strip) : 0 @lines.each_slice(@screen.height) do |lines| @linenum += @screen.height next if @linenum < prev Page.new(lines, @screen, @stats).run loop do suggestions = @stats.suggestions break if suggestions.empty? Page.new(pick(suggestions), @screen, @stats).run end end end |
#save ⇒ Object
20 21 22 |
# File 'lib/teletype/paginator.rb', line 20 def save File.write(@pagefile, @linenum) if @linenum.positive? end |
#split(text, length) ⇒ Object
47 48 49 50 51 52 53 54 55 |
# File 'lib/teletype/paginator.rb', line 47 def split(text, length) lines = [] text.each_line do |line| line.chars.each_slice(length) do |slice| lines << slice.join end end lines end |