ruby
43 lines · 7 steps
Batching monthly email summaries in Rails
A service object slices opted-in recipients into fixed-size batches, builds payloads, and enqueues mail with an audit log per batch.
Explained by
highlit
1class ReportBatcher
2 BATCH_SIZE = 500
3
4 def initialize(account)
5 @account = account
6 end
7
8 def deliver_monthly_summaries
9 pending_recipients.each_slice(BATCH_SIZE).with_index(1) do |batch, page|
10 Rails.logger.info("Dispatching summary batch ##{page} (#{batch.size} recipients)")
11
12 summaries = build_summaries_for(batch)
13 SummaryMailer.bulk_deliver(summaries).deliver_later
14
15 @account.delivery_logs.create!(
16 page: page,
17 recipient_ids: batch.map(&:id),
18 delivered_at: Time.current
19 )
20 end
21 end
22
23 private
24
25 def pending_recipients
26 @account.users
27 .active
28 .where(monthly_summary_opt_in: true)
29 .order(:created_at)
30 .to_a
31 end
32
33 def build_summaries_for(batch)
34 batch.map do |user|
35 {
36 user_id: user.id,
37 email: user.email,
38 metrics: MetricsAggregator.new(user).last_month,
39 generated_at: Time.current
40 }
41 end
42 end
43end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Slicing a large collection into fixed-size batches keeps memory and mailer load predictable at scale.
- 2Enqueuing work with deliver_later moves heavy delivery off the request path into background jobs.
- 3Recording a log row per batch gives you a replayable audit trail of what was sent and to whom.
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/batching-monthly-email-summaries-in-rails-explained-ruby-b686/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.