Fork me on GitHub
Hoopla! - now with extra whiz-bang home

The main problem I have with the rails default ./config/database.yml format is that it’s not DRY. Here’s an example of a default database config:

    development:
      adapter: mysql
      database: development_db
      username: username
      password: password
      sochost:  localhost
    test:
      adapter: mysql
      database: testing_db
      username: username
      password: password
      sochost:  localhost
    production:
      adapter: mysql
      database: production_db
      username: username
      password: password
      sochost:  localhost
  

Now, thanks to the Typo team (who have also made this blog possible), we have an alternative format that you can use to keep the redundancies out of your file:

    login: &login
      username: username
      password: password
      adapter:  mysql
      host:     localhost

    development:
      database: development_db
      <<: *login

    test:
      database: testing_db
      <<: *login

    production:
      database: production_db
      <<: *login
  

If this isn’t slick enough for you, Doug Alcorn has improved upon this by letting you change the login details for each host that you might run this application on. His code:

    login: &login
      username: username
      password: password
      adapter:  mysql
      host:     localhost

    # replace the above login details with information from ./config/dblogin.yml
    <%= file = File.join(RAILS_ROOT, "config", "dblogin.yml")
        IO.read(file) if File.exist?(file) %>

    development:
      database: development_db
      <<: *login

    test:
      database: testing_db
      <<: *login

    production:
      database: production_db
      <<: *login
  

And then you can have a separate file next to database.yml called dblogin.yml - and it can be different for each host. Here’s an example of what dblogin.yml could look like:

    login: &login
      username: danger
      password: jesus_was_probably_good_at_juggling
      adapter:  mysql
      host:     localhost
  
blog comments powered by Disqus