Skip to content

Commit

Permalink
Memoize the Paginator#page method
Browse files Browse the repository at this point in the history
This method is invoked multiple times to retrieve the `start_cursor`,
the `end_cursor`, and ultimately to return the actual `page` record.
By memoizing it, we avoid it from mapping over the `records` again and
again and rebuilding all the cursors every time it is invoked.
  • Loading branch information
nicolas-fricke committed Apr 19, 2021
1 parent 7c9bdf0 commit 29c1ce8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ These are the latest changes on the project's `master` branch that have not yet

### Fixed
- Only trigger one SQL query to load the records from the database and use it to determine if there was a previous / is a next page
- Memoize the `Paginator#page` method which is invoked multiple times to prevent it from mapping over the `records` again and again and rebuilding all cursors

### Added
- Description about `order_by` on arbitrary SQL to README.md
Expand Down
12 changes: 7 additions & 5 deletions lib/rails_cursor_pagination/paginator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,13 @@ def page_info
#
# @return [Array<Hash>] List of hashes, each with a `cursor` and `data`
def page
records.map do |item|
{
cursor: cursor_for_record(item),
data: item
}
memoize :page do
records.map do |item|
{
cursor: cursor_for_record(item),
data: item
}
end
end
end

Expand Down

0 comments on commit 29c1ce8

Please sign in to comment.