class Kwipper::Paginator
Constants
- PAGE_PARAM_NAME
- Page
Attributes
count[R]
from[R]
to[R]
Public Class Methods
new(model_class, page: 1, per: 20, path: '')
click to toggle source
# File lib/kwipper/paginator.rb, line 8 def initialize(model_class, page: 1, per: 20, path: '') @model_class, @path = model_class, path @page = [page.to_i, 1].max @per = [per.to_i, 1].max @count = @model_class.count @from = calc_offset + 1 @to = [calc_offset + @per, @count].min end
Public Instance Methods
current_page()
click to toggle source
# File lib/kwipper/paginator.rb, line 50 def current_page pages[@page - 1] end
get(statement)
click to toggle source
# File lib/kwipper/paginator.rb, line 17 def get(statement) @model_class.all "#{statement} LIMIT #{@per} OFFSET #{calc_offset}" end
next_page_path()
click to toggle source
# File lib/kwipper/paginator.rb, line 44 def next_page_path next_page = current_page.num next_page = [next_page, pages.size - 1].min pages[next_page].path end
on_first_page?()
click to toggle source
# File lib/kwipper/paginator.rb, line 30 def on_first_page? @page == 1 end
on_last_page?()
click to toggle source
# File lib/kwipper/paginator.rb, line 34 def on_last_page? pages.last.current? end
pages()
click to toggle source
# File lib/kwipper/paginator.rb, line 21 def pages @pages ||= begin (0...@count).step(@per).each_with_index.map do |_, num| num += 1 Page.new path_for(num), num, num == @page end end end
prev_page_path()
click to toggle source
# File lib/kwipper/paginator.rb, line 38 def prev_page_path prev_page = current_page.num - 1 prev_page = [prev_page, 1].max pages[prev_page - 1].path end
Private Instance Methods
add_query(hash)
click to toggle source
# File lib/kwipper/paginator.rb, line 64 def add_query(hash) URI.parse(@path).tap do |p| hash = Rack::Utils.parse_query(p.query).merge! hash p.query = Rack::Utils.build_query hash end.to_s end
calc_offset()
click to toggle source
# File lib/kwipper/paginator.rb, line 56 def calc_offset (@page - 1) * @per end
path_for(num)
click to toggle source
# File lib/kwipper/paginator.rb, line 60 def path_for(num) num == 1 ? @path : add_query(PAGE_PARAM_NAME => num) end