我的Rails(3.2.21)应用程序会发送大量电子邮件,而且它经常在开发和登台环境中测试因此,只要电子邮件正文中有url,主机名就需要与环境匹配。例子:
偏差:http://localhost:3000/something
分期: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

在我的mailer类中,到处都有这些难看的条件,有一个url要显示,因为我需要在dev中说明端口,如下所示:
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

我在这里缺少什么最佳实践我应该在mailer类中的任何方法之前将上面的条件语句放在一次上面,然后设置一个@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,它将根据环境的不同而不同

10-05 20:33
查看更多