nived.hari
Mon Sep 30 2024
Pagy Gem for Efficient Pagination in Rails
A fast, lightweight, and efficient solution for pagination in Ruby on Rails applications.
Why pagy?
- Faster and less resource heavy when compared to other pagination gems like Kaminari or Will Paginate
- Highly customizable : We can easily configure pagy through
pagy.rb
initializer file like default items per page.etc - "Helpful" Helpers : Pagy provides various helper methods that make it easy to implement pagination in views with minimal code.
- Efficiency: It significantly reduces the number of queries, making it ideal for large datasets.
- Performance-Oriented: Pagy is claiming to perform up to 40x faster than other pagination gems such as Kaminari and Will Paginate Example Usage:
Code for basic pagination:
In the controllers (e.g. application_controller.rb
)
include Pagy::Backend
In the Helpers (e.g. application_helper.rb
)
include Pagy::Frontend
Wrap your collections with pagy in your actions :
@pagy, @records = pagy(Product.all)
Optionally set your defaults in the pagy initializer pagy.rb
:
# Set default items per page and navigation size
Pagy::DEFAULT[:items] = 10 # items per page
Pagy::DEFAULT[:size] = [1, 4, 4, 1] # control how many navigation links are shown
In the view
:
<%= pagy_nav(@pagy) %>
-
pagy_nav
: Renders the full pagination navigation links (next, previous, and page numbers). -
pagy_info
: Displays pagination information such as the range of items being shown and the total count. Some additional helpers: -
pagy.from
: This returns the starting index of the current page’s items. -
<http://pagy.to|pagy.to>
: This returns the ending index of the current page’s items. -
pagy.count
: This returns the total number of items being paginated.
Example Usage:
Showing <%= pagy.from(@pagy) %> to <%= pagy.to(@pagy) %> of <%= @pagy.count %> items.
If we are on page 1 and displaying 8 items per page and total count is 20, This would display Showing 1 to 8 of 20 items
Giving more clarity about the pagination, making it user-friendly
#pagy #pagination #RubyOnRails