How to Manage Your database.yml

01 Jun 2006

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
  • Nitin said: Dear Sir, I m student , i m very actracted to the ruby on rails. I m trying to expor my knoledge, I have problem, i want to read another yml fils say 'xyz.yml' having configuration settings for another database. now how do i get this settings in my ruby code, in order to access that variables defined in the yml file. I want to able to parse the content of the yml file. Plese give me some idea how to so that? thanks in advance, looking forward to your reply, thanks, Nitin Jadav
  • Danger said: Hello Nitin! Lucky for you it's quite easy: `my_object = YAML::load_file('xyz.yml')` Or, if you've got <% %> tags in it (like on this page) you'll want: `my_object = YAML::load(ERB.new(IO.read('xyz.yml')).result)` You can learn more at RailsForum.com. The people there are very smart and good at answering questions. Good luck with your work!

Please if you found this post helpful or have questions.