-
Notifications
You must be signed in to change notification settings - Fork 10
/
bulk_subscriber_list_email_builder.rb
62 lines (50 loc) · 1.34 KB
/
bulk_subscriber_list_email_builder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class BulkSubscriberListEmailBuilder
include Callable
BATCH_SIZE = 5000
def initialize(subject:, body:, subscriber_lists:)
@subject = subject
@body = body
@subscriber_lists = subscriber_lists
@now = Time.zone.now
end
def call
ActiveRecord::Base.transaction do
batches.flat_map do |subscription_ids|
records = records_for_batch(subscription_ids)
Email.insert_all!(records).pluck("id")
end
end
end
private
attr_reader :subject, :body, :subscriber_lists, :now
def records_for_batch(subscription_ids)
subscriptions = Subscription
.includes(:subscriber, :subscriber_list)
.find(subscription_ids)
subscriptions.map do |subscription|
subscriber = subscription.subscriber
{
address: subscriber.address,
subject: subject,
body: email_body(subscriber, subscription),
subscriber_id: subscriber.id,
created_at: now,
updated_at: now,
}
end
end
def email_body(subscriber, subscription)
<<~BODY
#{BulkEmailBodyPresenter.call(body, subscription.subscriber_list)}
---
#{FooterPresenter.call(subscriber, subscription)}
BODY
end
def batches
Subscription
.active
.where(subscriber_list: subscriber_lists)
.dedup_by_subscriber
.each_slice(BATCH_SIZE)
end
end