I have this class to send an mail, using rails 7
class Mailer < ApplicationMailer
def initialize(emails)
super()
@emails = emails
end
def send()
mail(
to: @emails,
from: '[email protected]' ,
subject: 'example'
)
end
end
I want to inject at initialize an Mailer class
class MailService
def initialize(sender:)
@sender= sender
end
def submit_mail
@sender.send().deliver_now
# @sender.send().deliver //work but i need use deliver_now
end
end
i am using like this:
mailer = Mailer.new('[email protected]')
MailService.submit_mail(sender: mailer)
I am getting this error
NoMethodError: undefined method `deliver_now' for #<Mail::Message:1026960, Multipart: true ...
Did you mean? deliver
Error
As indicated by the error message
Mail::Messagedoes not implement#deliver_now. This method is implemented inActionMailer::MessageDeliveryIssue
You have run into rails magic.
Typical implementation of a Mailer is: (taken from the docs)
When you call
NotifierMailer::welcomethis is actually handled by method_missing because#welcomeis an instance method rather than a class instance method, as might be suggested by the call pattern.The method missing then returns an
Actionmailer::MessageDeliveryobject not an instance ofNotifierMaileror aMail::Message(as the method body would suggest).Resolution
Redefine your mailer as
Note: I changed
sendtosend_emailbecauseObjectalready definessendand that means themethod_missingwould not be invoked.Then you could:
A) Use the Mailer the way it was designed (Recommended)
B) Utilize the above to modify your service
Note: your post said you were using
MailService.call(sender: mailer); however this would have resulted in aNoMethodErrorof its own sincecallis not a class instance method ofMailService, so I assumed this was a simple typo