Module: BetterController::Pagination

Extended by:
ActiveSupport::Concern
Defined in:
lib/better_controller/pagination.rb

Overview

Module providing pagination functionality for ActiveRecord collections

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#paginate(collection, page: nil, per_page: nil) ⇒ ActiveRecord::Relation

Paginate a collection

Parameters:

  • collection (ActiveRecord::Relation)

    The collection to paginate

  • page (Integer) (defaults to: nil)

    The page number

  • per_page (Integer) (defaults to: nil)

    The number of items per page

Returns:

  • (ActiveRecord::Relation)

    The paginated collection



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/better_controller/pagination.rb', line 13

def paginate(collection, page: nil, per_page: nil)
  page     = (page || params[:page] || 1).to_i
  per_page = (per_page || params[:per_page] || 25).to_i

  paginated = collection.page(page).per(per_page)

  # Add pagination metadata
  if respond_to?(:add_meta)
    add_meta(:pagination, {
               current_page: paginated.current_page,
               total_pages:  paginated.total_pages,
               total_count:  paginated.total_count,
               per_page:     per_page,
             })
  end

  paginated
end