Quick guide how to use Pagy with Sinatra and Sequel

Victor Afanasev
Aug 3, 2018 · 2 min read

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'


require 'sinatra/base'
require 'pagy'
require 'pagy/extras/bootstrap'
class App < Sinatra::Base
include Pagy::Backend
helpers do
include Pagy::Frontend
get "/posts" do
# where Post is a Sequel model
@pagy, @posts = pagy(Post)
erb :'posts/index'

def pagy_get_vars(collection, vars)
count: collection.count,
page: params["page"],
items: vars[:items] || 25

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

<div class="row">
<div class="col-lg-12">
<h1>All Posts</h1>

<% @posts.each do |post| %>
<h2><%= post.title %></h2>
<p><%= post.description %></p>
<% end %>
<%= pagy_nav_bootstrap(@pagy) if @pagy.pages > 1 %>


  • include Pagy::Backend backend pagy methods included to the controller
  • Inside helpers do block we are including frontend pagy methods for views with extra bootstrap pagination helper.
  • def pagy_get_varsit’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.

That’s all, now run Sinatra app and go to http://localhost:4567/posts?page=2 and you’ll see nice pagination made by Pagy:

Image for post
Image for post

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store