]> git.openstreetmap.org Git - rails.git/blob - app/controllers/concerns/pagination_methods.rb
Merge branch 'pull/5206'
[rails.git] / app / controllers / concerns / pagination_methods.rb
1 module PaginationMethods
2   extend ActiveSupport::Concern
3
4   private
5
6   ##
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
11
12     id_column = "#{items.table_name}.id"
13     page_items = if params[:before]
14                    items.where("#{id_column} < ?", params[:before]).order(:id => :desc)
15                  elsif params[:after]
16                    items.where("#{id_column} > ?", params[:after]).order(:id => :asc)
17                  else
18                    items.order(:id => :desc)
19                  end
20
21     page_items = page_items.limit(limit)
22     page_items = page_items.includes(includes)
23     page_items = page_items.sort.reverse
24
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])
27
28     [page_items, newer_items_id, older_items_id]
29   end
30 end