Skip to content

Instantly share code, notes, and snippets.

@chussenot
Forked from dblock/cursor_helper.rb
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chussenot/a6797c848a48d7b254e6 to your computer and use it in GitHub Desktop.
Save chussenot/a6797c848a48d7b254e6 to your computer and use it in GitHub Desktop.
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