forked from sendgrid/sendgrid-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
personalization.rb
93 lines (73 loc) · 2.12 KB
/
personalization.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
require 'json'
module SendGrid
class Personalization
attr_reader :tos, :from, :ccs, :bccs, :headers, :substitutions, :custom_args,
:dynamic_template_data
attr_accessor :send_at, :subject
def initialize
@tos = []
@from = nil
@ccs = []
@bccs = []
@subject = nil
@headers = {}
@substitutions = {}
@custom_args = {}
@dynamic_template_data = {}
@send_at = nil
end
def add_to(to)
raise DuplicatePersonalizationError if duplicate?(to)
@tos << to.to_json
end
def add_from(from)
@from = from.to_json
end
def add_cc(cc)
raise DuplicatePersonalizationError if duplicate?(cc)
@ccs << cc.to_json
end
def add_bcc(bcc)
raise DuplicatePersonalizationError if duplicate?(bcc)
@bccs << bcc.to_json
end
def add_header(header)
header = header.to_json
@headers = @headers.merge(header['header'])
end
def add_substitution(substitution)
substitution = substitution.to_json
@substitutions = @substitutions.merge(substitution['substitution'])
end
def add_custom_arg(custom_arg)
custom_arg = custom_arg.to_json
@custom_args = @custom_args.merge(custom_arg['custom_arg'])
end
def add_dynamic_template_data(dynamic_template_data)
@dynamic_template_data.merge!(dynamic_template_data)
end
def to_json(*)
{
'to' => tos,
'from' => from,
'cc' => ccs,
'bcc' => bccs,
'subject' => subject,
'headers' => headers,
'substitutions' => substitutions,
'custom_args' => custom_args,
'dynamic_template_data' => dynamic_template_data,
'send_at' => send_at
}.delete_if { |_, value| value.to_s.strip == '' || value == [] || value == {} }
end
private
def duplicate?(addition)
additional_email = addition.email.downcase
[@tos, @ccs, @bccs].flatten.each do |elm|
return true if elm&.dig('email')&.downcase == additional_email
end
false
end
end
class DuplicatePersonalizationError < StandardError; end
end