ruby
23 lines · 6 steps
Building a weekly digest email in Rails
A mailer action queries a user's unread notifications, groups them for the view, and skips sending when there's nothing to report.
Explained by
highlit
1class DigestMailer < ApplicationMailer
2 default from: "notifications@example.com"
3
4 def weekly_digest(user)
5 @user = user
6 notifications = user.notifications
7 .unread
8 .includes(:notifiable)
9 .where(created_at: 1.week.ago..Time.current)
10 .order(created_at: :desc)
11
12 @grouped = notifications.group_by { |n| n.created_at.to_date }
13 @channels = notifications.group_by(&:channel)
14 @total = notifications.size
15
16 return if @total.zero?
17
18 mail(
19 to: user.email,
20 subject: "You have #{@total} new #{'notification'.pluralize(@total)}"
21 )
22 end
23end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Chaining scopes with includes avoids N+1 queries when the mail template renders associated records.
- 2Precomputing grouped collections in the action keeps view templates simple and logic-free.
- 3A guard clause lets a mailer opt out of sending entirely when there's no content worth delivering.
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-weekly-digest-email-in-rails-explained-ruby-500e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.