Skip to content

Instantly share code, notes, and snippets.

@dblock
Created October 20, 2014 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dblock/26b6b859c8c939b5bf3d to your computer and use it in GitHub Desktop.
Save dblock/26b6b859c8c939b5bf3d to your computer and use it in GitHub Desktop.
Pagination in a Grape API with Roar.
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