Module: Apes::Concerns::Pagination

Included in:
Apes::Controller
Defined in:
lib/apes/concerns/pagination.rb

Overview

Pagination handling module.

Instance Method Summary (collapse)

Instance Method Details

- (ActiveRecord::Relation) paginate(collection, sort_field: :id, sort_order: :desc)

Paginates a collection according to the current cursor.

Parameters:

  • collection (ActiveRecord::Relation)

    The collection to paginate.

  • sort_field (Symbol)

    The field to use for pagination.

  • sort_order (Symbol)

    The order to use for pagination.

Returns:

  • (ActiveRecord::Relation)

    The paginated collection.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/apes/concerns/pagination.rb', line 16

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

- (Symbol) pagination_field

The field to use for pagination.

Returns:

  • (Symbol)

    The field to use for pagination.



37
38
39
# File 'lib/apes/concerns/pagination.rb', line 37

def pagination_field
  @pagination_field ||= :handle
end

- (Boolean) pagination_skip?

Whether to skip pagination. This is used by template generation.

Returns:

  • (Boolean)

    true if pagination must be skipped in template, false otherwise.



44
45
46
# File 'lib/apes/concerns/pagination.rb', line 44

def pagination_skip?
  @skip_pagination
end

- (Boolean) pagination_supported?

Checks if current collection supports pagination. This is used by template generation.

Returns:

  • (Boolean)

    true if pagination is supported, false otherwise.



51
52
53
# File 'lib/apes/concerns/pagination.rb', line 51

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

- (String) pagination_url(page = nil)

Returns the URL a specific page of the current collection.

Parameters:

  • page (Symbol) (defaults to: nil)

    The page to return.

Returns:

  • (String)

    The URL for a page of the current collection.



59
60
61
62
# File 'lib/apes/concerns/pagination.rb', line 59

def pagination_url(page = nil)
  exist = @cursor.might_exist?(page, @objects)
  exist ? url_for(request.params.merge(page: @cursor.save(@objects, page, field: pagination_field)).merge(only_path: false)) : nil
end