DRier database.yml

01Oct08

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!

Advertisements


No Responses Yet to “DRier database.yml”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: