DRY database config with Rails

Posted 06/06/2006 by dnaffis 0 CommentsAdd Your Comment

During the process of installing Typo I noticed something interesting in the database.yml file.

It turns out that the Rails database config file is written in YAML (http://www.yaml.org/) which is a data serialization format with a lot of nifty features. I just skimmed through the specs which can be found here: http://yaml.org/spec/current.html

Anyway, one of my pet peeves so far with setting up applications has been rewriting database config information. For small non-production projects I don’t use separate test, development, and production databases. Or sometimes the username, password and host are the same for each database. So why repeat that information over and over and over? Turns out you can save yourself a few lines of editing by doing something like this:

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

development:
  database: myapp_development
  <<: *login

test:
  database: myapp_test
  <<: *login

production:
  database: myapp_production
  <<: *login

Leave a Reply

Dave is the cofounder of Intridea and leads Intridea's product development efforts.

Before Intridea, Dave spent years at both AOL and IMAKE and received a Masters in Systems Engineering from the University of Virginia.