在哪里设置轨道/分期/生产的主机名



我的导轨(3.2.21)应用程序发送了很多电子邮件,并且经常在开发和登台环境中进行测试。结果,每当电子邮件主体中有URL时,主机名都需要匹配环境。示例:

  • dev:http://localhost:3000/sosings
  • 舞台:http://example.staging.com/something
  • 生产:http://example.com/something

当前,我在initializers/setup_email.rb中有一个初始化器,该初始化程序根据环境设置ActionMailer::Base.default_url_options[:host]变量(此初始化程序还设置了其他电子邮件设置FWIW)。 staging 例如ActionMailer::Base.default_url_options[:host] = "example.staging.com"

dev 有条件块具有:host :port,因此看起来像这样:

ActionMailer::Base.default_url_options[:host] = "localhost"
ActionMailer::Base.default_url_options[:port] = 3000

在我的邮件类课程中,我到处都有这些丑陋的条件可以显示,因为我需要在开发人员中考虑端口。这样:

if Rails.env.production? || Rails.env.staging?
    @url = "http://#{ActionMailer::Base.default_url_options[:host]}/something"
elsif Rails.env.development?
    @url = "http://#{ActionMailer::Base.default_url_options[:host]}:#{ActionMailer::Base.default_url_options[:port]}/something"
end

我在这里想念什么最好的做法?我是否应该在任何方法之前都在我的邮件类上面的上述条件语句,所以我一次设置一个@host变量,然后忘记它?

我认为最简单的方法是定义development.rbproduction.rbstaging.rb中的自定义常数。

类似:

# development.rb
mailer_host = ActionMailer::Base.default_url_options[:host] = "localhost"
mailer_port = ActionMailer::Base.default_url_options[:port] = 3000
MailerURL = "http://#{mailer_host}:#{mailer_port}"
# production.rb
mailer_host = ActionMailer::Base.default_url_options[:host] = "foo.com"
MailerURL = "http://#{mailer_host}"

这样,您可以避免条件。只需使用MailerURL,它会有所不同,具体取决于环境

您还可以将其保存为环境变量ENV["HOST_URL"]

最新更新