module Ballast::Concerns::JSONApi::PaginationHandling
A concern to handle errors. It requires the Ajax concern.
Public Instance Methods
Paginates a collection.
@param collection [ActiveRecord::Relation] The collection to handle. @param sort_field [Symbol] The field to sort on. @param sort_order [Symbol] The sorting order. return [ActiveRecord::Relation] A paginated and sorted collection.
# File lib/ballast/concerns/json_api/pagination_handling.rb, line 17 def paginate(collection, sort_field: :id, sort_order: :desc) direction = @cursor.direction value = @cursor.value # Apply the query collection = apply_value(collection, value, sort_field, sort_order) collection = collection.limit(@cursor.size).order(sprintf("%s %s", sort_field, sort_order.upcase)) # If we're fetching previous we reverse the order to make sure we fetch the results adiacents to the previous request, # then we reverse results to ensure the order requested if direction != "next" collection = collection.reverse_order collection = collection.reverse end collection end
Returns the field used for pagination.
@return [Symbol] The field used for pagination.
# File lib/ballast/concerns/json_api/pagination_handling.rb, line 38 def pagination_field @pagination_field ||= :id end
Returns whether pagination should be skipped in templates rendering for JSON API.
@return [Boolean] Whether pagination should be skipped.
# File lib/ballast/concerns/json_api/pagination_handling.rb, line 45 def pagination_skip? @skip_pagination end
Returns whether pagination is supported for the current set of objects for JSON API.
@return [Boolean] Whether pagination is supported.
# File lib/ballast/concerns/json_api/pagination_handling.rb, line 52 def pagination_supported? @objects.respond_to?(:first) && @objects.respond_to?(:last) end
Returns a URL to get a specific page of the current set of objects.
@param key [String] The page to get. Supported values are `next`, `prev`, `previous` and `first`. @return [String] A URL.
# File lib/ballast/concerns/json_api/pagination_handling.rb, line 60 def pagination_url(key = nil) exist = @cursor.might_exist?(key, @objects) exist ? url_for(request.params.merge(page: @cursor.save(@objects, key, field: pagination_field)).merge(only_path: false)) : nil end