-
-
Save chussenot/a6797c848a48d7b254e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Api | |
module V2 | |
module Util | |
module CursorHelpers | |
extend ActiveSupport::Concern | |
# apply cursor-based pagination to a collection | |
# returns a hash: | |
# results: (paginated collection subset) | |
# next: (cursor to the next page) | |
def paginate_by_cursor(coll) | |
raise 'Both cursor and offset parameters are present, these are mutually exclusive.' if params.key?(:offset) && params.key?(:cursor) | |
results = { results: [], next: nil } | |
size = (params[:size] || 5).to_i | |
if params.key?(:offset) | |
skip = params[:offset].to_i | |
coll = coll.skip(skip) | |
end | |
coll.limit(size).scroll(params[:cursor]) do |record, next_cursor| | |
results[:results] << record | |
results[:next] = next_cursor.to_s | |
end | |
results[:total_count] = coll.count if params[:total_count] && coll.respond_to?(:count) | |
results | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment