Created
July 31, 2012 19:58
-
-
Save abevoelker/3219985 to your computer and use it in GitHub Desktop.
Convert Ruby hash keys to dotted form like backbone-deep-model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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