【问题标题】:MailGun + Devise + Rails = "uninitialized constant MyMailer::MailGun"?MailGun + Devise + Rails = “未初始化的常量 MyMailer::MailGun”?
【发布时间】:2020-02-29 20:07:17
【问题描述】:

我使用 Devise 进行身份验证,使用 mailgun-ruby gem 发送电子邮件,我很难弄清楚如何使 Devise 的默认邮件程序类与 Mailgun 一起使用。根据 mailgun 文档,我已将 production.rb 文件配置为使用 mailgun 设置:

config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
 api_key: ENV['MAILGUN_API_KEY'],
 domain: 'mail.mywebsite.com'
}

然后在我的邮件类中,我需要 gem 并实例化一个 Mailgun::Client 对象。

class MyMailer < Devise::Mailer
  require 'mailgun-ruby'
  helper :application
  include Devise::Controllers::UrlHelpers
  default template_path: 'users/mailer'

 def confirmation_instructions(record, token, opts={})
  mg_client = MailGun::Client.new
  message_params = {
   from: "me@mywebsite.com",
   to: record.email,
   subject: "Please confirm your account"
  }

  mg_client.send_message message_params

  super
 end
end

我在 devise.rb 初始化程序中注释掉了config.mailer = 'MyMailer' 行,但出于某种原因,Rails 正在寻找 MailGun 作为 MyMailer 的子类。为什么是这样?错误在标题中 - uninitialized constant MyMailer::MailGun

【问题讨论】:

  • 另外,您需要将require 移出课堂。把它放在文件的顶部。
  • 你是我见过的第一个这样说的人,我见过的每个代码示例都将它放在类中。把它放在课外有什么好处?
  • 这就像许多编程语言的约定。开发者可以看到这个类包含了哪些模块。不确定它对 Rails 有什么影响。我能想象的唯一情况 - 加载很少使用的模块,它可以节省一些内存,但我不是 100% 确定这一点。 UPD:这里有一些关于 stackoverflow.com/questions/605261/… 的讨论

标签: ruby-on-rails devise mailgun


【解决方案1】:

您的代码中似乎有拼写

mg_client = MailGun::Client.new

应该是

mg_client = Mailgun::Client.new

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多