Posted by
eric
on
July 28, 2010
Use YAML's anchor and reference syntax to DRY up your database.yml file.
Use anchors (&) and references (*) to merge options allowing your database.yml to not be so repetitive. Obviously you can organize in a way that makes the most sense to your organization but the following is an example where the database and test environments share some config and the production and staging environment share some config. So rather than repeating them you we just tag the first one with an anchor and then merge it (<<) into the next def with a reference (*).
development: &sqlite
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
test:
<<: *sqlite
database: db/test.sqlite3
staging: &mysql
adapter: mysql
encoding: utf8
socket: /tmp/mysql.sock
username: admin
password: password
database: staging
production:
<<: *mysql
database: production

Comments
http://blog.tinogomes.com/2008/03/23/dry-configdatabaseyml/
1. database.yml is always ignored from source code version controller, so you can't share this code to other developers.
2. I always define the database as necessary, e.g. development and test database in my local environment, only staging database in staging server and only production database in production server.
It's too small benefits for me to use the & and <<.
Also nice mention on this trick being useful for other YAML files. I don't use YAML for much but sometimes plugins/gems use them for configuration so this trick is useful for any of those files.