Class: Warped::Queries::Paginate

Inherits:
Object
  • Object
show all
Defined in:
lib/warped/queries/paginate.rb

Overview

Paginate a scope

This class provides a way to paginate a scope and return the metadata.

To see the maximum number of records per page and the default number of records per page, check the MAX_PER_PAGE and DEFAULT_PER_PAGE constants.

Examples:

Warped::Queries::Paginate.call(User.all, page: 2, per_page: 10)
# => [{ total_count: 100, total_pages: 10, next_page: 3, prev_page: 1, page: 2, per_page: 10 }, <ActiveRecord::Relation [...]>]

See Also:

Constant Summary collapse

MAX_PER_PAGE =
100
DEFAULT_PER_PAGE =
10

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, page: nil, per_page: nil) ⇒ Array<Hash, ActiveRecord::Relation>

Returns the metadata and the paginated scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to paginate

  • page (Integer) (defaults to: nil)

    the page number

  • per_page (Integer) (defaults to: nil)

    the number of records per page



36
37
38
39
40
41
# File 'lib/warped/queries/paginate.rb', line 36

def initialize(scope, page: nil, per_page: nil)
  super()
  @scope = scope
  @page = page
  @per_page = per_page
end

Class Method Details

.call(scope, page: nil, per_page: nil) ⇒ Array<Hash, ActiveRecord::Relation>

Returns the metadata and the paginated scope.

Parameters:

  • scope (ActiveRecord::Relation)

    the scope to paginate

  • page (Integer) (defaults to: nil)

    the page number

  • per_page (Integer) (defaults to: nil)

    the number of records per page

Returns:

  • (Array<Hash, ActiveRecord::Relation>)

    the metadata and the paginated scope



28
29
30
# File 'lib/warped/queries/paginate.rb', line 28

def self.call(scope, page: nil, per_page: nil)
  new(scope, page:, per_page:).call
end

Instance Method Details

#callObject



43
44
45
46
47
48
# File 'lib/warped/queries/paginate.rb', line 43

def call
  offset = (page - 1) * per_page
  paginated_scope = scope.limit(per_page).offset(offset)

  [(scope), paginated_scope]
end