puppetlabs/puppetlabs-stdlib — pull request #147 by mhellmic (2013-04-22 21:44:23+00:00)
Title: don't fail on undef variable in merge

I'll explain the change, why I'd like it, and how I implemented it in the following.

Proposed change:
if merge gets passed an undefined variable, it doesn't fail with an exception, but instead silently ignores the value

Use case:
In my configuration file, one parameter can be repeatedly set with different values. Both key and value are variable, so I use a hash. Based on the input, different values are used, so I create multiple hashes, combine them with merge and then pass them to the template as one (the template is part of a more generic puppet module and should not know about the different internal hashes I created).

Because some value are used, merge fails and I would have to check first for all combinations and then call merge in the right way.
I have three hashes to combine so I already have to check for nine combinations, for somebody with more it's even less feasible.

I'll sketch the code here:

if one {
var1 = { abc => 123, bcd => 234 }
}
if two {
var2 = { def => 456 }
}
if three { ... }

var = merge(var1, var2, var3) # might fail if one is undef

Code change:
Add a check for .empty? for every argument. Good, because it filters everything that is not empty: string, lists, ... . Bad, because you could get away with passing a wrong type in some cases, get an exception in others. Unfortunately, puppets undef doesn't seem to map to anything useful in ruby. We can use arg == "", but that's only slightly better.
Any other ideas are most welcome!