Reputation: 489
My Rails (3.2.21) app sends a lot of email, and it's frequently tested in dev and staging environments. As a result, whenever there's a URL in the email body, the host name needs to match the environment. Example:
Currently, I have an initializer in initializers/setup_email.rb
that sets the ActionMailer::Base.default_url_options[:host]
variable depending on the environment (this initializer also sets up other email settings fwiw). Staging for instance is ActionMailer::Base.default_url_options[:host] = "example.staging.com"
.
The dev conditional block however has a :host
AND :port
, so it looks like this:
ActionMailer::Base.default_url_options[:host] = "localhost"
ActionMailer::Base.default_url_options[:port] = 3000
In my mailer classes, I have these ugly conditionals everywhere there's a URL to display, since I need to account for port in dev. Like this:
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
What best practice am I missing here? Should I just have the above conditional statement once atop my mailer class before any methods, so I set a @host
variable once and forget it?
Upvotes: 3
Views: 4076
Reputation: 26778
I think the easiest way is to define a custom constant in development.rb
, production.rb
, and staging.rb
.
Something like:
# 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}"
That way you can avoid the conditionals. Just use MailerURL
and it will be different depending on the environment
Upvotes: 1