Pagy is a modern pagination gem for Ruby. It works out of box with Rails and ActiveRecord (check out Quick Start guide here).

Pagy is very effective and lightweight, so it’s a good idea to use it with Sinatra and Sequel ORM. We need to adjust some settings though, let’s see how to do it.

First add to Gemfile pagy gem:

gem 'pagy'

app.rb:

require 'sinatra/base'

require 'pagy'

require 'pagy/extras/bootstrap' class App < Sinatra::Base

include Pagy::Backend helpers do

include Pagy::Frontend

end get "/posts" do

# where Post is a Sequel model

@pagy, @posts = pagy(Post)

erb :'posts/index'

end private



def pagy_get_vars(collection, vars)

{

count: collection.count,

page: params["page"],

items: vars[:items] || 25

}

end

end

views/posts/index.erb (Also don’t forget to include views/layout.erb)



<div class="col-lg-12">

<h1>All Posts</h1>



<%

<h2><%= post.title %></h2>

<p><%= post.description %></p>

<% end %> All Posts @posts .each do |post| %>

</div>

</div> @pagy ) if @pagy.pages > 1 %>

Where

include Pagy::Backend backend pagy methods included to the controller

backend pagy methods included to the controller Inside helpers do block we are including frontend pagy methods for views with extra bootstrap pagination helper.

block we are including frontend pagy methods for views with extra bootstrap pagination helper. def pagy_get_vars it’s a special pagy method to override default logic and tell pagy how to work with custom environment than Rails. Count: pagy uses collection.count(:all) to get total size of records of model (ActiveRecord). It didn’t work for Sequel and correct solution will be collection.count . Page: provide current page param.