Ryan Fisher Ryan Fisher - 1 year ago 55
Ruby Question

What's a good approach for loading a YAML config in Ruby but setting default values?

I am going to load some app configurations from a YAML file:

# YAML config file
app_name: "Example"
app_path: ~/path/to/app

So I load them:

app_config = YAML::load_file("config.yml")

What would be a clean way to set defaults if some key/value is missing?

Answer Source

Since app_config would simply be a Hash at the point that you've loaded your YAML config, you can use Hash-like tests, like this:

name = app_config['name'] || 'default'

This works great if you have a very minimal number of these checks to make, particularly if they're located right near the point that you load the YAML config.

However, you can update your config hash with the defaults, like this:

app_config['name'] ||= 'default'

That way, you don't have to keep checking to see if the key exists throughout the rest of your code.

Something like this at the point that you load the YAML might work:

app_config = YAML::load_file("config.yml")

# Set default values
app_config['app_name'] ||= "Example"
app_config['app_path'] ||= "~/path/to/app"

That will keep the rest of your code simple and uncomplicated by applying default values. These are DRY defaults for YAML config files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download