Skip to content

Pagination ​

Runcobo::Pagination turns a page number and page size into a safe offset and limit. Combine it with a contract for the input and a query that takes LIMIT and OFFSET:

db/queries/posts.sql
sql
-- name: ListPostsPage :many
SELECT id, author_id, title, status FROM posts
ORDER BY id DESC
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
crystal
class PageContract < RequestValidation::Contract
  schema do
    optional :page, Int32
    optional :per_page, Int32
  end
end

class Posts::ListPosts < Blog::BaseAction
  get "/posts"

  call do
    input = validate(PageContract)
    pagination = Runcobo::Pagination.new(input.page, input.per_page)
    posts = store.list_posts_page(row_limit: pagination.per_page, row_offset: pagination.offset.to_i32)
    render_json({
      page:     pagination.page,
      per_page: pagination.per_page,
      posts:    posts.map { |post| {id: post.id, title: post.title} },
    })
  end
end

pagination.offset is an Int64; the generated method takes an Int32 here, hence .to_i32.

Normalization ​

Out-of-range values are clamped instead of raising, so a hand-edited URL can't produce a negative offset or an unbounded page:

Input page, per_pagepageper_pageoffset
nil, nil1200
3, 1031020
0, 101100
2, 5002100100
1, 0 or negative1200

Change the defaults with default_per_page: and max_per_page::

crystal
Runcobo::Pagination.new(input.page, input.per_page, default_per_page: 50, max_per_page: 200)

In-memory lists ​

slice returns the current page of an array:

crystal
pagination = Runcobo::Pagination.new(2, 10)
pagination.slice((1..35).to_a)   # => [11, 12, ..., 20]

Validate or clamp?

Pagination clamps silently. If you'd rather reject bad input with a 422, add constraints to the contract, e.g. optional :per_page, Int32, gteq: 1, lteq: 100.

Released under the MIT License.