Rails 7 正在尝试使用 .deliver 而不是 Deliver_now

问题描述 投票:0回答:1

我有这个类来发送邮件,使用rails 7

class Mailer < ApplicationMailer
  def initialize(emails)
    super()
    @emails = emails
  end 

  def send()
    mail(
      to: @emails,
      from: '[email protected]' ,
      subject: 'example'
    )
  end
end

我想在初始化 Mailer 类时注入

class MailService 
    prepend SimpleCommand
  
    def initialize(sender:)
      @sender= sender
    end    

    def call
      @sender.send().deliver_now
      # @sender.send().deliver //work but i need use deliver_now 
    end 
  end

我这样使用:

mailer = Mailer.new('[email protected]')
MailService.call(sender: mailer)

我收到此错误

NoMethodError:未定义方法“deliver_now”#

ruby-on-rails mailgun
1个回答
0
投票

错误

如错误消息所示

Mail::Message
未实现
#deliver_now
。此方法由
Actionmailer::MessageDelivery

提供

问题

您遇到了 Rails 魔法。 Mailer 的典型实现是

class NotifierMailer < ApplicationMailer
  def welcome(recipient)
    attachments.inline['photo.png'] = File.read('path/to/photo.png')
    mail(to: recipient, subject: "Here is what we look like")
  end
end

当您调用

NotifierMailer#welcome
时,这实际上是由 method_missing 处理的,因为
#welcome
是实例方法而不是类实例方法,正如调用模式所建议的那样。

缺少的方法返回一个

Actionmailer::MessageDelivery
对象,而不是
NotifierMailer
Mail::Message
的实例(如方法主体所建议的那样)。

分辨率

将您的邮件程序重新定义为

class Mailer < ApplicationMailer

  def send(emails)
    @emails = emails
    mail(
      to: @emails,
      from: '[email protected]' ,
      subject: 'example'
    )
  end
end

然后你可以:

A) 按照设计方式使用邮件程序(推荐)

Mailer.send('[email protected]').deliver_now

B) 利用上述内容修改您的服务

class MailService 
  prepend SimpleCommand
  
  def initialize(sender:, action:, emails: )
    @sender= sender
    @action = action
    @emails = emails
  end    

  def call
    @sender.public_send(:action, emails).deliver_now
    # or ActionMailer::MessageDelivery(sender, action, emails)
  end 
end
© www.soinside.com 2019 - 2024. All rights reserved.