根据条件交付方式?导轨

use*_*921 5 development-environment ruby-on-rails actionmailer

Rails 4.1.4,我有很多类 Mailers,它们都有不同的传递方法。现在这给我带来了一个问题。

在开发和测试环境中,当我有delivery_method时,:test如果我使用下面的类执行和交付,那么交付方法就变成了:custom_method,即使我config.delivery_method = :test在rails环境文件中提到过。

class CustomMailer < ActionMailer::Base

  default :delivery_method => :custom_method,
          from: "...",
          reply_to: '...'

  def emailer(emails)
    mail(to: emails, subject: 'test')
  end

end
Run Code Online (Sandbox Code Playgroud)

在开发和测试环境中更改:custom_methodto的正确方法是什么?:test

我已经实施的一种可行的解决方案是:

class CustomMailer < ActionMailer::Base

  DELIVERY_METHOD = Rails.env == 'production' ? :custom_method : :test

  default :delivery_method => DELIVERY_METHOD,
          from: "...",
          reply_to: '...'

  def emailer(emails)
    mail(to: emails, subject: 'test')
  end

end
Run Code Online (Sandbox Code Playgroud)

这对我有用,但我觉得这不是一个好方法,因为我必须写这一行:

DELIVERY_METHOD = Rails.env == 'production' ? :custom_method : :test
Run Code Online (Sandbox Code Playgroud)

在每个 Mailer 类中,这可能会导致冗余。如果能以某种常见的方式处理那就太好了。

请注意,每个 Mailer 类别都有不同的传递方法。

gka*_*ats 4

您采用的方法当然有效,但我相信在代码中查询 Rails.env 是一种反模式。

您可以通过设置自定义配置属性来使用应用程序配置。这是一个例子:

# config/production.rb
Rails.application.configure do
  # by having this configured by an environment variable 
  # you can have different values in staging, 
  # develop, demo, etc.. They all use "production" env.
  config.x.mailer_livemode = ENV['MAILER_LIVEMODE']
end

# config/development.rb
Rails.application.configure do
  config.x.mailer_livemode = false
end

# config/test.rb
Rails.application.configure do
  config.x.mailer_livemode = false
end

# app/mailers/custom_mailer.rb
default delivery_method: Rails.application.config.x.mailer_livemode ? :custom_method : :test
Run Code Online (Sandbox Code Playgroud)

灵活性优越。您可以让多个配置变量一起工作,delivery_method在配置中直接设置等。

最重要的是,您不会依赖与电子邮件发送方式无关的东西(Rails.env)。