module RocketPants::Pagination

Pagination support for RocketPants

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

@author Alessandro Desantis <desa.alessandro@gmail.com>

Constants

RESERVED_PAGINATION_KEYS

Reserved root keys

VERSION

Public Instance Methods

expose_with_pagination(hash) click to toggle source

Exposes the given collection with pagination metadata.

@param [Hash{Symbol => ActiveRecord::Relation}] a hash with exactly one

element, its key being the root key and its value a paginated relation

@raise [ArgumentError] if the hash is malformed

# 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 = {}) click to toggle source

Paginates the given relation.

The page param is ‘page’ by default.

@param [ActiveRecord::Relation] the relation to paginate @param [Hash] an options hash for the paginate method

@return [ActiveRecord::Relation] a paginated relation

# File lib/rocket_pants/pagination.rb, line 34
def paginate(relation, options = {})
  relation.paginate({ page: params[:page] }.merge(options))
end
paginate_and_expose(hash) click to toggle source

Paginates and exposes the given collection with pagination metadata.

Basically, just calls {#paginate}, then {#expose_with_pagination}.

@param [Hash(Symbol => ActiveRecord::Relation)] a hash with exactly one

element, its key being the root key and its value a paginated relation

@raise [ArgumentError] if the hash is malformed

# 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

Private Instance Methods

extract_pagination_elements_from(hash) click to toggle source
# File lib/rocket_pants/pagination.rb, line 82
def extract_pagination_elements_from(hash)
  validate_pagination_hash! hash
  hash.first
end
validate_pagination_hash!(hash) click to toggle source
# File lib/rocket_pants/pagination.rb, line 87
def validate_pagination_hash!(hash)
  fail(
    ArgumentError,
    "The hash should contain exactly 1 element (#{hash.size} given)"
  ) if hash.size != 1

  fail(
    ArgumentError,
    "#{hash.keys.first} is a reserved root key"
  ) if hash.keys.first.to_sym.in?(RESERVED_PAGINATION_KEYS)
end