I want a mailer class (let's say UserMailer
) to call a method on another mailer class (let's say LoggerMailer
) when UserMailer
's method is called. My code is like this:
app/mailers/logger_mailer.rb
class LoggerMailer < ActionMailer::Base
def log_mail(...)
...
mail(layout: ..., template: ..., to: ..., from: ..., subject: ..., ...)
end
end
app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
def some_mail_method(...)
...
LoggerMailer.log_mail(...)
mail(layout: ..., to: ..., from: ..., subject: ..., ...)
end
end
UserMailer#some_mail_method
is the main mail method, and when this is called, I want it to call LoggerMailer#log_mail
in addition to its own mail
method call.
However, when I call UserMailer#some_mail_method
, it does not seem to call LoggerMailer#log_mail
. I feel so because when I put a line binding.pry
within the method body of LoggerMailer#log_mail
, it does not seem to stop at that point.
- Is
LoggerMailer.log_mail
actually called? - In general, is it possible or not to call a mailer method from the method body of another mailer method?
Your problem is that mailer methods don't send anything on their own, they (by calling
mail
) just returnActionMailer::MessageDelivery
instances and then someone callsdeliver_now
ordeliver_later
on thatActionMailer::MessageDelivery
to actually arrange delivery.When you do this:
you're calling the mailer but throwing away the
ActionMailer::MessageDelivery
that it returns so nothing useful happens.You need to deliver the log mail:
You could also put the
LoggerMailer.log_mail
andUserMailer. some_mail_method
messages in a wrapper that would forward thedeliver_now
ordeliver_later
methods when the caller gets around to trying to deliver thesome_mail_method
.