ruby
60 lines · 9 steps
Building a paginated activity feed in Rails
A single class merges several ActiveRecord sources into one sorted, paginated, renderable stream.
Explained by
highlit
1class ActivityFeed
2 include Enumerable
3
4 Entry = Struct.new(:record, :type, :occurred_at, keyword_init: true) do
5 def to_partial_path
6 "activities/#{type}"
7 end
8 end
9
10 DEFAULT_PER_PAGE = 25
11
12 def initialize(user, page: 1, per_page: DEFAULT_PER_PAGE)
13 @user = user
14 @page = [page.to_i, 1].max
15 @per_page = per_page.to_i.clamp(1, 100)
16 end
17
18 def each(&block)
19 entries.each(&block)
20 end
21
22 def entries
23 @entries ||= merged.slice(offset, @per_page) || []
24 end
25
26 def next_page?
27 merged.size > offset + @per_page
28 end
29
30 def next_page
31 next_page? ? @page + 1 : nil
32 end
33
34 private
35
36 def offset
37 (@page - 1) * @per_page
38 end
39
40 def merged
41 @merged ||= sources
42 .flat_map { |type, scope| wrap(scope, type) }
43 .sort_by { |entry| -entry.occurred_at.to_i }
44 end
45
46 def sources
47 limit = offset + @per_page
48 {
49 comment: @user.comments.recent.limit(limit),
50 post: @user.posts.published.recent.limit(limit),
51 follow: @user.received_follows.recent.limit(limit)
52 }
53 end
54
55 def wrap(scope, type)
56 scope.map do |record|
57 Entry.new(record: record, type: type, occurred_at: record.created_at)
58 end
59 end
60end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Including Enumerable and defining each gives your object the full collection API for free.
- 2Normalizing heterogeneous records into a common Struct lets you merge and sort them uniformly.
- 3Memoization plus bounded input sizes keeps a multi-source feed cheap to build and safe to paginate.
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/building-a-paginated-activity-feed-in-rails-explained-ruby-71ac/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.