ruby
41 lines · 8 steps
A reusable pagination concern in Rails
A controller concern that safely paginates any scope and exposes page metadata through response headers.
Explained by
highlit
1module Paginatable
2 extend ActiveSupport::Concern
3
4 private
5
6 def paginate(scope)
7 page = params.fetch(:page, 1).to_i
8 per_page = [params.fetch(:per_page, 25).to_i, 100].min
9 per_page = 25 if per_page < 1
10
11 total = scope.count
12 total_pages = (total.to_f / per_page).ceil
13 page = page.clamp(1, [total_pages, 1].max)
14
15 records = scope.limit(per_page).offset((page - 1) * per_page)
16
17 set_pagination_headers(page, per_page, total, total_pages)
18 records
19 end
20
21 def set_pagination_headers(page, per_page, total, total_pages)
22 response.set_header("X-Total-Count", total.to_s)
23 response.set_header("X-Total-Pages", total_pages.to_s)
24 response.set_header("X-Page", page.to_s)
25 response.set_header("X-Per-Page", per_page.to_s)
26
27 links = {
28 first: page_url(1, per_page),
29 prev: (page > 1 ? page_url(page - 1, per_page) : nil),
30 next: (page < total_pages ? page_url(page + 1, per_page) : nil),
31 last: page_url([total_pages, 1].max, per_page)
32 }.compact
33
34 header = links.map { |rel, url| %(<#{url}>; rel="#{rel}") }.join(", ")
35 response.set_header("Link", header) if header.present?
36 end
37
38 def page_url(page, per_page)
39 url_for(request.query_parameters.merge(page: page, per_page: per_page, only_path: false))
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Clamping and capping user-supplied paging params guards against absurd offsets and unbounded page sizes.
- 2Emitting pagination state as response headers keeps JSON payloads clean and API-friendly.
- 3Wrapping the logic in a concern lets any controller paginate an ActiveRecord scope with one call.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-reusable-pagination-concern-in-rails-explained-ruby-0c3b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.