HashFlatten gem provides a Hash#squish_levels
method which takes values from all sub hashes and stores them in the top level under key which is constructed as concatenation of all sub level keys. So from this: { a: { b: 'c' } }
you get this: { 'a.b' => 'c' }
. It also has a method for reverse operation.
I extracted it into a gem because i already use it for two things:
The code itself is about 30 LOC and is pretty simple:
I made it as a Ruby Refinement because i wanted to see how it works and how is it useful. So far so good :)
Look inside README how to use it or copy the code above directly.
If you copy and modify it i suggest to always test for two sneaky cases:
I didn't notice these bugs immediately and found out pretty late. But they are now properly tested of course :)
Please let me know if you find this useful or have any suggestion with the code. Thanks, Přemek