Email Digest Background Process

Curated ago by @jeremysmithco

Description

This set of Sidekiq workers queries a set of email digest subscribers and performs a fan-out to send email to each subscriber as a separate job.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class DigestSender
  include Sidekiq::Worker

  def perform(digest_id, subscription_id)
    digest = Digest.find(digest_id)
    subscription = Subscription.find(subscription_id)
    return if subscription_unsendable?(subscription)
    user = subscription.user
    return if user_unsendable?(user)

    if DigestMailer.digest(user, digest).deliver_now
      subscription.touch(:last_sent_at)
    end
  end

  def subscription_unsendable?(subscription)
    subscription.sent_recently? || subscription.unsubscribed?
  end

  def user_unsendable?(user)
    user.blank? || user.email.blank?
  end
end

This worker loads the digest, subscription, and user, checks if the email can be sent, and if it can, sends the email, touching the last_sent_at timestamp.