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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
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.