Skip to content

Instantly share code, notes, and snippets.

@abevoelker
Created July 31, 2012 19:58
Show Gist options
  • Save abevoelker/3219985 to your computer and use it in GitHub Desktop.
Save abevoelker/3219985 to your computer and use it in GitHub Desktop.
Convert Ruby hash keys to dotted form like backbone-deep-model
class Hash
def hflatten(path=[])
self.inject({}) do |a,(k,v)|
if v.is_a? Hash
# Recurse
a.merge(v.hflatten(path.dup << k))
else
# Base case
a[(path.dup << k).join('.')] = v; a
end
end
end
end
require 'hflatten'
require 'test/unit'
class TestHflatten < Test::Unit::TestCase
def test_hflatten
h = {
'user' => {
'name' => {
'first' => 'John',
'last' => 'Doe'
}
},
'greeting' => 'Howdy!'
}
expected = {
'user.name.first' => 'John',
'user.name.last' => 'Doe',
'greeting' => 'Howdy!'
}
assert_equal(expected, h.hflatten)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment