Advertisement
Guest User

Untitled

a guest
Jun 25th, 2016
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. module Api
  2. module Helpers
  3. module CursorHelpers
  4. extend ActiveSupport::Concern
  5.  
  6. # apply cursor-based pagination to a collection
  7. # returns a hash:
  8. # results: (paginated collection subset)
  9. # next: (cursor to the next page)
  10. def paginate_by_cursor(coll, &_block)
  11. raise 'Both cursor and offset parameters are present, these are mutually exclusive.' if params.key?(:offset) && params.key?(:cursor)
  12. results = { results: [], next: nil }
  13. size = (params[:size] || 10).to_i
  14. if params.key?(:offset)
  15. skip = params[:offset].to_i
  16. coll = coll.skip(skip)
  17. end
  18. # some items may be skipped with a block
  19. query = block_given? ? coll : coll.limit(size)
  20. query.scroll(params[:cursor]) do |record, next_cursor|
  21. record = yield(record) if block_given?
  22. results[:results] << record if record
  23. results[:next] = next_cursor.to_s
  24. break if results[:results].count >= size
  25. end
  26. results[:total_count] = coll.count if params[:total_count] && coll.respond_to?(:count)
  27. results
  28. end
  29.  
  30. def paginate_and_sort_by_cursor(coll, options = {}, &block)
  31. Hashie::Mash.new(paginate_by_cursor(sort(coll, options), &block))
  32. end
  33. end
  34. end
  35. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement