class Paginator

Attributes

current_page[R]
list[R]
per_page[R]

Public Class Methods

new(list) click to toggle source
# File lib/chid/paginator.rb, line 7
def initialize(list)
    @current_page = 1
    @per_page     = 3
    @list         = list.freeze
end

Public Instance Methods

paginate(&block) click to toggle source
# File lib/chid/paginator.rb, line 13
def paginate(&block)
    begin_index = (current_page - 1) * per_page
    end_index   = (current_page * per_page) - 1
    
    return if list.size < begin_index

    paginated_list = list.slice(begin_index..end_index)

    paginated_list.each do |object|
        block.(object) if block_given?
    end

    ask_action(&block)
end

Private Instance Methods

ask_action(&block) click to toggle source
# File lib/chid/paginator.rb, line 29
def ask_action(&block)
    return if total_pages <= 1

    puts "\n#{current_page} of #{total_pages}"

    puts "\nPrevious(p) Next(n) Quit(q):"
    print "> "
    option = STDIN.gets.strip

    return        if (/^q/.match(option))
    next_page     if (/^n/.match(option))
    previous_page if (/^p/.match(option))

    paginate(&block)
end
next_page() click to toggle source
# File lib/chid/paginator.rb, line 45
def next_page
    @current_page += 1
end
previous_page() click to toggle source
# File lib/chid/paginator.rb, line 49
def previous_page
    @current_page -= 1
end
total_pages() click to toggle source
# File lib/chid/paginator.rb, line 53
def total_pages
    list.size / per_page
end