在Rails中,如何设置开发/暂存/生产环境的主机名?

3
我的Rails(3.2.21)应用程序发送了大量的电子邮件,并且经常在开发和暂存环境中进行测试。因此,每当电子邮件正文中有一个URL时,主机名需要与环境匹配。例如: 目前,我有一个位于initializers/setup_email.rb的初始化程序,根据环境设置ActionMailer::Base.default_url_options[:host]变量(此初始化程序还设置其他电子邮件设置)。例如,暂存环境ActionMailer::Base.default_url_options[:host] = "example.staging.com"
然而,开发环境的条件块有一个:host :port,所以它看起来像这样:
ActionMailer::Base.default_url_options[:host] = "localhost"
ActionMailer::Base.default_url_options[:port] = 3000

在我的邮件类中,每当需要显示一个URL时,我都会有很多丑陋的条件语句,因为我需要考虑开发环境中的端口。就像这样:
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变量并忘记它即可?
2个回答

1
我认为最简单的方法是在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,它会根据环境而有所不同。

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接