Module: Ballast::Concerns::JSONApi::PaginationHandling

Defined in:
lib/ballast/concerns/json_api/pagination_handling.rb

Overview

A concern to handle errors. It requires the Ajax concern.

Instance Method Summary collapse

Instance Method Details

#paginate(collection, sort_field: :id, sort_order: :desc) ⇒ Object

Paginates a collection.

return [ActiveRecord::Relation] A paginated and sorted collection.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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

#pagination_fieldSymbol

Returns the field used for pagination.



38
39
40
# File 'lib/ballast/concerns/json_api/pagination_handling.rb', line 38

def pagination_field
  @pagination_field ||= :id
end

#pagination_skip?Boolean

Returns whether pagination should be skipped in templates rendering for JSON API.



45
46
47
# File 'lib/ballast/concerns/json_api/pagination_handling.rb', line 45

def pagination_skip?
  @skip_pagination
end

#pagination_supported?Boolean

Returns whether pagination is supported for the current set of objects for JSON API.



52
53
54
# File 'lib/ballast/concerns/json_api/pagination_handling.rb', line 52

def pagination_supported?
  @objects.respond_to?(:first) && @objects.respond_to?(:last)
end

#pagination_url(key = nil) ⇒ String

Returns a URL to get a specific page of the current set of objects.



60
61
62
63
# 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