Skip to content

Commit d78e263

Browse files
committed
Add :condition option to dynamically evaluate if an email should be intercepted
1 parent 56db680 commit d78e263

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,14 @@ Optionally prefix the subject line:
3434
subject_prefix: '[STAGING]'
3535
)
3636

37+
Optionally intercept emails :
38+
39+
Mail.register_interceptor RecipientInterceptor.new(
40+
ENV['EMAIL_RECIPIENTS'],
41+
condition: lambda { |message| message.subject =~ /Error/ } # if the condition proc return true the email is intercepted
42+
)
43+
44+
3745
Credits
3846
-------
3947

lib/recipient_interceptor.rb

+2
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ class RecipientInterceptor
44
def initialize(recipients, options = {})
55
@recipients = normalize_to_array(recipients)
66
@subject_prefix = options[:subject_prefix]
7+
@condition = options[:condition]
78
end
89

910
def delivering_email(message)
11+
return if @condition && !@condition.call(message)
1012
add_custom_headers message
1113
add_subject_prefix message
1214
message.to = @recipients

spec/recipient_interceptor_spec.rb

+36
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,42 @@
5959
expect(response.subject).to eq '[STAGING] some subject'
6060
end
6161

62+
describe 'with a :condition option' do
63+
64+
it 'does not intercept if condition proc evaluate to false' do
65+
Mail.register_interceptor RecipientInterceptor.new(
66+
recipient_string,
67+
condition: lambda { |m| false }
68+
)
69+
70+
response = deliver_mail
71+
72+
expect(response.to).to eq ['[email protected]']
73+
end
74+
75+
it 'does intercept if condition proc evaluate to true' do
76+
Mail.register_interceptor RecipientInterceptor.new(
77+
recipient_string,
78+
condition: lambda { |m| true }
79+
)
80+
81+
response = deliver_mail
82+
83+
expect(response.to).to eq [recipient_string]
84+
end
85+
86+
it 'pass the message object to the condition proc' do
87+
Mail.register_interceptor RecipientInterceptor.new(
88+
recipient_string,
89+
condition: lambda { |m| m.to == ['[email protected]'] }
90+
)
91+
92+
response = deliver_mail
93+
94+
expect(response.to).to eq [recipient_string]
95+
end
96+
end
97+
6298
def recipient_string
6399
64100
end

0 commit comments

Comments
 (0)