caikesouza

Keeping your YAML clean

It’s not uncommon to find Ruby applications that contain YAML files with unnecessary duplication. Long configuration files make it difficult for developers to effectively maintain application-wide settings.

The YAML specification offers some neat features that we can use to reduce duplication and keep files organized.

image


In this blog post, I’m going to explain how to use anchors and aliases within YAML files.

Anchors and Aliases

The YAML format offers a simple form of inheritance, which allows new properties to reference values from previously defined properties. This is referenced in the YAML spec as anchors and aliases.

Taken from the spec:

Repeated nodes (objects) are first identified by an anchor (marked with the ampersand - “&”), and are then aliased (referenced with an asterisk - “*”) thereafter.

To understand how this works, let’s review a common Rails app example:

# config/database.yml
development:
  username: root
  password: secret
  log_level: debugger
  database: my_app_development

test:
  username: root
  password: secret
  log_level: debugger
  database: my_app_test

staging:
  username: root
  password: secret
  log_level: debugger
  database: my_app_staging

The following example uses the same values for username, password and log_level for all three environments. Let’s re-write the previous example using an anchor and an alias.

First, we define an anchor called base for the values defined in the development group:

# config/database.yml
development: &base
  username: root
  password: secret
  log_level: debugger
  database: my_app_development

Then, we create an alias for that anchor from the other groups:

# config/database.yml
test:
  <<: *base
  
staging:
  <<: *base

This brings all information defined in the base anchor and includes it in test and staging.

Finally, we override test and staging with what’s specific to those two groups. In this case, the value for database is shown as:

# config/database.yml
test:
  <<: *base
  database: my_app_test
  
staging:
  <<: *base
  database: my_app_staging

The final version now looks like this:

# config/database.yml
development: &base
  username: root
  password: secret
  log_level: debugger
  database: my_app_development

test:
  <<: *base
  database: my_app_test

staging:
  <<: *base
  database: my_app_staging

This is a much cleaner version that is way easier to understand.

Care for your YAML

Using anchors and aliases is very simple. Although the syntax might feel a little weird at first, it’s easy to get used to and it’s a great way to keep your configuration files under control.

Do you have any other tips that may help keep YAML files clean and maintainable? Please leave a comment and let us know.

- Carlos Souza (@caike)

(photo source: http://www.flickr.com/photos/nels/4346988512)

10.28.13 ← See All Posts
blog comments powered by Disqus