]> git.openstreetmap.org Git - rails.git/blob - app/controllers/concerns/pagination_methods.rb
Fix new rubocop warnings
[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, cursor_column: :id)
9     param! :before, Integer, :min => 1
10     param! :after, Integer, :min => 1
11
12     qualified_cursor_column = "#{items.table_name}.#{cursor_column}"
13     page_items = if params[:before]
14                    items.where("#{qualified_cursor_column} < ?", params[:before]).order(cursor_column => :desc)
15                  elsif params[:after]
16                    items.where("#{qualified_cursor_column} > ?", params[:after]).order(cursor_column => :asc)
17                  else
18                    items.order(cursor_column => :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_cursor = page_items.first&.send cursor_column
26     older_items_cursor = page_items.last&.send cursor_column
27
28     [
29       page_items,
30       (newer_items_cursor if page_items.any? && items.exists?(["#{qualified_cursor_column} > ?", newer_items_cursor])),
31       (older_items_cursor if page_items.any? && items.exists?(["#{qualified_cursor_column} < ?", older_items_cursor]))
32     ]
33   end
34 end