Rails & Devise: how to configure mail with domain name automatically?

2.5k views Asked by At

I need some advice on configuring mail in production Ruby-on-Rails sites.

I deploy my Rails app on EngineYard. I have a couple of sites, like demo.mydomain.com or staging.mydomain.com - how can I configure Devise so that at deploy time I can make sure confirmation mails come from demo.mydomain.com or staging.mydomain.com automatically? ie, I want the same GitHub codebase, and want to fill the configuration in dynamically.

Currently in config/environments/production.rb I have the line:

config.action_mailer.default_url_options = { :host => 'demo.mydomain.com' }

But that's incorrect when the same code is deployed to staging.mydomain.com as they both run in RAILS_ENV=production

Any ideas?

Thanks, Dave

Update: For now, to be practical, I've added specific environments to hardcode the mailer domain. So now demo.mydomain.com runs on environments/demo.rb, and www.mydomain.com runs on environments/productions.rb. What I don't like about this is the duplication between the files, it's not clear to me how to DRY them up as I have with, eg, database.yml

3

There are 3 answers

2
phoet On BEST ANSWER

in your devise configuration, usually config/initializers/devise.rb you can configure the mail-sender for devise. this configuration takes a proc, so that it's possible to evaluate something at runtime.

Devise.setup do |config|
  config.mailer_sender = Proc.new { your_magic_here }
end
3
Sandip Ransing On

Ideally staging & production servers should run on different rails environment. Still if you wanted to have production env running on both staging & production servers with different action mailer urls then it should be done at deployment level. You can always write environment file while deployment.

0
Carlos André Oliveira On

First of all, I think you should separate the environments of your application. Check this guide to learn how you can do it.

Then, try something like this in your devise configuration:

Devise.setup do |config|
  if Rails.env.production?
    config.mailer_sender = "[email protected]"
  elsif Rails.env.staging?
    config.mailer_sender = "[email protected]"
  else
    config.mailer_sender = "[email protected]"
  end
  ...

Check this guide to understand more about Proc object.