Skip to content

Commit

Permalink
Add universal paginator to use page/per on search
Browse files Browse the repository at this point in the history
  • Loading branch information
NuckChorris committed Sep 21, 2023
1 parent 846b094 commit ea0a08f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
8 changes: 8 additions & 0 deletions app/resources/anime_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ def self._search_service
AnimeSearchService if Flipper[:typesense_search].enabled?(User.current)
end

def self._paginator
if Flipper[:typesense_search].enabled?(User.current)
:universal
else
JSONAPI.configuration.default_paginator
end
end

def self.updatable_fields(context)
super - [:nsfw]
end
Expand Down
41 changes: 41 additions & 0 deletions lib/universal_paginator.rb
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

0 comments on commit ea0a08f

Please sign in to comment.