-
Notifications
You must be signed in to change notification settings - Fork 142
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add universal paginator to use page/per on search
- Loading branch information
1 parent
846b094
commit ea0a08f
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
# frozen_string_literal: true | ||
|
||
class UniversalPaginator < JSONAPI::Paginator | ||
attr_reader :params | ||
|
||
def initialize(params) | ||
@params = params | ||
# Initialize sub-paginator | ||
paginator | ||
end | ||
|
||
def offset? | ||
params[:offset].present? || params[:limit].present? | ||
end | ||
|
||
def page? | ||
!!offset? | ||
end | ||
|
||
def paginator | ||
@paginator ||= paginator_class.new(params) | ||
end | ||
|
||
def paginator_class | ||
offset? ? OffsetPaginator : PagedPaginator | ||
end | ||
|
||
delegate :calculate_page_count, to: :paginator | ||
delegate :links_page_params, to: :paginator | ||
|
||
def apply(relation, _order_options) | ||
if offset? | ||
paginator.apply(relation, _order_options) | ||
else | ||
# We apply the PagedPaginator logic ourselves because it uses offset/limit | ||
# We want to have page/per method calls to be applied to the relation | ||
relation = relation.page(params[:number]) if params[:number].present? | ||
relation = relation.per(params[:size]) if params[:size].present? | ||
end | ||
end | ||
end |