When we create a new Rails project a database.yml is created for us, and it looks like this one:

development:
  adapter: mysql
  encoding: utf8
  database: project_development
  username: root
  password: password
  socket: /var/run/mysqld/mysqld.sock

test:
  adapter: mysql
  encoding: utf8
  database: project_test
  username: root
  password: password
  socket: /var/run/mysqld/mysqld.sock

production:
  adapter: mysql
  encoding: utf8
  database: project_production
  username: root
  password: password
  socket: /var/run/mysqld/mysqld.sock

But, RoR is strongly based on DRY (Don’t Repeat Yourself) concept. And, as we can see, we have a lot of duplicated lines here.

If we pay attention, some lines of the database.yml file are repeated on development, test and production databases, and for most of the projects we have this databases on the same local. So, we have some lines repeated:

  adapter: mysql
  encoding: utf8
  username: root
  password: password
  socket: /var/run/mysqld/mysqld.sock

Googling, you can find a “DRY database.yml” scratched like this one:

login: &login
  adapter: mysql
  username: root
  password: password
  socket: /var/run/mysqld/mysqld.sock

development:
  <<: *login
  database: project_development

test:
  <<: *login
  database: project_test

production:
  <<: *login
  database: project_production

But, for me we still have some duplicated lines, and I don’t like it. So here goes the “DRier database.yml”:

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

<% ["development", "test", "production"].each do |environment| %>
<%= environment %>:
  <<: *login
  database: project_<%= environment %>
<% end %>

Enjoy it!



No Responses Yet to “DRier database.yml”  

  1. No Comments Yet

Leave a Reply