Skip to content

Instantly share code, notes, and snippets.

@shamess
Created November 19, 2023 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamess/cb4a0851687c45b9d701e2d0f5773742 to your computer and use it in GitHub Desktop.
Save shamess/cb4a0851687c45b9d701e2d0f5773742 to your computer and use it in GitHub Desktop.
class BookSearchPaginator
DEFAULT_CURSOR = {
current_query_index: 0,
current_page_number: 1,
current_item: 0
}.freeze
def initialize(ordered_queries, &auth_block)
@ordered_queries = ordered_queries
@auth_block = auth_block
end
def next(page_size: 12, cursor: DEFAULT_CURSOR)
results = []
new_cursor = cursor
auth_block.call do
(page_results, new_cursor) = fetch_results_from_cursor(number_needed: page_size, cursor:)
results += page_results
while results.size < page_size
break if ordered_queries[new_cursor.fetch(:current_query_index)].nil?
(page_results, new_cursor) = fetch_results_from_cursor(number_needed: page_size - results.size, cursor: new_cursor)
break if results.empty?
results += page_results
end
end
[results, new_cursor]
end
private
attr_reader :ordered_queries, :auth_block
def fetch_results_from_cursor(number_needed:, cursor:)
current_query_index = cursor.fetch(:current_query_index)
current_item = cursor.fetch(:current_item)
current_page = ordered_queries[current_query_index]
.page(cursor.fetch(:current_page_number))
.all
results = current_page.slice(cursor.fetch(:current_item), number_needed) || []
new_cursor = if results.size < number_needed
if current_page.pages.next_page
{
current_query_index:,
current_page_number: current_page.pages.next_page,
current_item: 0
}
else
{
current_query_index: current_query_index + 1,
current_page_number: 1,
current_item: 0
}
end
else
{
current_query_index:,
current_page_number: current_page.pages.current_page,
current_item: current_item + results.size
}
end
[results, new_cursor]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment