Reduce Duplication in database.yml Configuration in Ruby on Rails Project

By default rails generate database.yml that have the same attributes in each environment. So to reduce duplication we use aliasing to essentially perform a hash merge on the fly in the code.
So far so good please take a look the below code.

Before refactor

database.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
development:
  database: blog_development
  host: localhost
  username: your_database_username
  password: your_database_password
  adapter: mysql2
  encoding: utf8
  collation: utf8_unicode_ci

test:
  database: blog_test
  host: localhost
  username: your_database_username
  password: your_database_password
  adapter: mysql2
  encoding: utf8
  collation: utf8_unicode_ci

staging:
  database: blog_staging
  host: localhost
  username: your_database_username
  password: your_database_password
  adapter: mysql2
  encoding: utf8
  collation: utf8_unicode_ci

production:
  database: blog_production
  host: localhost
  username: your_database_username
  password: your_database_password
  adapter: mysql2
  encoding: utf8
  collation: utf8_unicode_ci

After refactor

database.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
defaults: &defaults
  username: your_database_username
  password: your_database_password
  adapter: mysql2
  encoding: utf8
  collation: utf8_unicode_ci

development:
  database: blog_development
  host: localhost
  <<: *defaults

test:
  database: blog_test
  host: localhost
  <<: *defaults

staging:
  database: blog_staging
  host: localhost
  <<: *defaults

production:
  database: blog_production
  host: localhost
  <<: *defaults