Got bit by an empty string in yaml
Posted on 02/26/2015
I had added a new key to the secrets.yml file in our Rails application. The value of that key was derived from an ENV variable within an erb tag. In order to avoid a nil value when the ENV variable isn't present, which it may or may not be depending on the particular environment, I used the fetch
method like so...
foo: <%= ENV.fetch('MY_VAR_NAME', '') %>
My intent was to have foo
default to an empty string, but sadly it didn't. Once the erb was evaluated, it resulted in yaml that looked like this...
foo:
And of course, when that yaml is loaded, foo
becomes nil. Not what I wanted. Instead, my yaml needed to look like this...
foo: ""
So I updated the secrets.yml file to look like this...
foo: <%= ENV.fetch('MY_VAR_NAME', '""') %>
And everything worked as expected.