1 module PaginationMethods
2 extend ActiveSupport::Concern
7 # limit selected items to one page, get ids of first item before/after the page
8 def get_page_items(items, includes: [], limit: 20)
9 param! :before, Integer, :min => 1
10 param! :after, Integer, :min => 1
12 id_column = "#{items.table_name}.id"
13 page_items = if params[:before]
14 items.where("#{id_column} < ?", params[:before]).order(:id => :desc)
16 items.where("#{id_column} > ?", params[:after]).order(:id => :asc)
18 items.order(:id => :desc)
21 page_items = page_items.limit(limit)
22 page_items = page_items.includes(includes)
23 page_items = page_items.sort.reverse
25 newer_items_id = page_items.first.id if page_items.count.positive? && items.exists?(["#{id_column} > ?", page_items.first.id])
26 older_items_id = page_items.last.id if page_items.count.positive? && items.exists?(["#{id_column} < ?", page_items.last.id])
28 [page_items, newer_items_id, older_items_id]