title: Where to set host name for dev/staging/production in Rails?
body: <p>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:</p>
  
  <ul>
  <li>Dev: <a href="http://localhost:3000/something" rel="nofollow">http://localhost:3000/something</a></li>
  <li>Staging: <a href="http://example.staging.com/something" rel="nofollow">http://example.staging.com/something</a></li>
  <li>Production: <a href="http://example.com/something" rel="nofollow">http://example.com/something</a></li>
  </ul>
  
  <p>Currently, I have an initializer in <code>initializers/setup_email.rb</code> that sets the <code>ActionMailer::Base.default_url_options[:host]</code> variable depending on the environment (this initializer also sets up other email settings fwiw). <strong>Staging</strong> for instance is <code>ActionMailer::Base.default_url_options[:host] = "example.staging.com"</code>. </p>
  
  <p>The <strong>dev</strong> conditional block however has a <code>:host</code> <strong>AND</strong> <code>:port</code>, so it looks like this:</p>
  
  <pre><code>ActionMailer::Base.default_url_options[:host] = "localhost"
  ActionMailer::Base.default_url_options[:port] = 3000
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>What best practice am I missing here? Should I just have the above conditional statement <em>once</em> atop my mailer class before any methods, so I set a <code>@host</code> variable once and forget it? </p>