In my mailer controller, under certain conditions (missing data) we abort sending the email.
How do I exit the controller method without still rendering a view in that case?
return if @some_email_data.nil?
Doesn't do the trick since the view is still rendered (throwing an error every place I try to use @some_email_data unless I add a lot of nil checks)
And even if I do the nil checks, it complains there's no 'sender' (because I supposed did a 'return' before getting to the line where I set the sender and subject.
Neither does render ... return
Basically, RETURN DOESN'T RETURN inside a mailer method!
A much simpler solution than the accepted answer would be something like:
class SomeMailer < ActionMailer::Base def some_method if @some_email_data.nil? self.message.perform_deliveries = false else mail(...) end end end
If you're using Rails 3.2.9 (or later things even better) - there you can finally conditionally call mail()
. Here's the related GitHub thread. Now the code can be reworked like this:
class SomeMailer < ActionMailer::Base def some_method unless @some_email_data.nil? mail(...) end end end
I just encountered same thing here.
My solution was following:
module BulletproofMailer class BlackholeMailMessage < Mail::Message def self.deliver false end end class AbortDeliveryError < StandardError end class Base < ActionMailer::Base def abort_delivery raise AbortDeliveryError end def process(*args) begin super *args rescue AbortDeliveryError self.message = BulletproofMailer::BlackholeMailMessage end end end end
Using these wrapper mailer would look like this:
class EventMailer < BulletproofMailer::Base include Resque::Mailer def event_created(event_id) begin @event = CalendarEvent.find(event_id) rescue ActiveRecord::RecordNotFound abort_delivery end end end
It is also posted in my blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With