Module: RocketPants::Pagination

Defined in:
lib/rocket_pants/pagination.rb,
lib/rocket_pants/pagination/version.rb

Overview

Pagination support for RocketPants

Include this module in your RocketPants controllers to add pagination support.

Author:

Constant Summary collapse

VERSION =
'2.0.0'

Instance Method Summary collapse

Instance Method Details

#expose_with_pagination(hash) ⇒ Object

Exposes the given collection with pagination metadata.

Parameters:

  • a (Hash{Symbol => ActiveRecord::Relation})

    hash with exactly one element, its key being the root key and its value a paginated relation

Raises:

  • (ArgumentError)

    if the hash is malformed



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rocket_pants/pagination.rb', line 46

def expose_with_pagination(hash)
  root_key, collection = extract_pagination_elements_from hash

  response = {
    root_key => ActiveModel::Serializer::CollectionSerializer.new(collection),
    count: collection.count,
    pagination: {
      pages: collection.total_pages,
      current: collection.current_page,
      count: collection.count,
      per_page: collection.per_page,
      previous: collection.previous_page,
      next: collection.next_page
    }
  }

  expose response
end

#paginate(relation, options = {}) ⇒ ActiveRecord::Relation

Paginates the given relation.

The page param is ‘page’ by default.

Parameters:

  • the (ActiveRecord::Relation)

    relation to paginate

  • an (Hash)

    options hash for the #paginate method

Returns:

  • (ActiveRecord::Relation)

    a paginated relation



34
35
36
# File 'lib/rocket_pants/pagination.rb', line 34

def paginate(relation, options = {})
  relation.paginate({ page: params[:page] }.merge(options))
end

#paginate_and_expose(hash) ⇒ Object

Paginates and exposes the given collection with pagination metadata.

Basically, just calls #paginate, then #expose_with_pagination.

Parameters:

  • a (Hash(Symbol => ActiveRecord::Relation))

    hash with exactly one element, its key being the root key and its value a paginated relation

Raises:

  • (ArgumentError)

    if the hash is malformed



75
76
77
78
# File 'lib/rocket_pants/pagination.rb', line 75

def paginate_and_expose(hash)
  root_key, collection = extract_pagination_elements_from hash
  expose_with_pagination root_key => paginate(collection)
end