Chris Snow
Chris Snow

Reputation: 24606

how to raise an exception if a variable read from yaml file is not declared in the yaml file?

I am reading variables from a yaml file:

begin
  settings = YAML.load_file 'vm.yaml'

  $var_a   = settings['var_a']
  $var_b   = settings['var_b']
  ....
  $var_z   = settings['var_z']

rescue
  puts "\nInvalid vm.yaml - please create or recreate vm.yaml from vm.yaml.example\n\n"
  exit 1
end

puts $var_a

If a variable is not set in the vm.yaml file, the error will not be detected until the variable is first accessed (e.g. at puts $var_a).

Preferably, I would like the code in the rescue block to be executed if the variable is not set in the yaml file.

What is the most rubyist way to do this?

Upvotes: 0

Views: 1426

Answers (1)

Alexis Andersen
Alexis Andersen

Reputation: 805

Use a fetch instead of [] to access the hash data.

So instead of settings['var_a'] do settings.fetch('var_a')

By default, this will raise an error if the key does not exist. But the fetch method also takes an optional block that is executed if the key isn't found.

This can allow you to set up a default return value: settings.fetch('var_a') { 'foo' }

or create a custom failure message:

settings.fetch('var_a') { fail "Key var_a was not found, please add it to the yaml" }

Upvotes: 3

Related Questions