Created
September 14, 2013 18:05
-
-
Save jgarber/6564171 to your computer and use it in GitHub Desktop.
Flatten deep hash of attributes into readable keys and values.
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
def make_one_dimensional(input = {}, output = {}, prefix = nil) | |
if input.respond_to?(:each) | |
input.each do |key, value| | |
key = [prefix, key].compact.join('.') | |
case value | |
when Hash | |
make_one_dimensional(value, output, key) | |
when Array | |
value.each_with_index do |v, index| | |
array_key = "#{key}[#{index}]" | |
make_one_dimensional(v, output, array_key) | |
end | |
else | |
output[key] = value | |
end | |
end | |
else | |
output[prefix] = input | |
end | |
output | |
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 'rspec' | |
require_relative 'make_one_dimensional' | |
describe 'make_one_dimensional' do | |
let(:h) do | |
{ | |
:a => { | |
:b => [1, 2, 3], | |
:c => [{:d => 4, :e => {:f => 5, :g => ['6', '6b']}}, {:h => 7}], | |
:i => '8' | |
}, | |
:j => 9 | |
} | |
end | |
it "should flatten" do | |
make_one_dimensional(h).should == { | |
'a.b[0]' => 1, | |
'a.b[1]' => 2, | |
'a.b[2]' => 3, | |
'a.c[0].d' => 4, | |
'a.c[0].e.f' => 5, | |
'a.c[0].e.g[0]' => '6', | |
'a.c[0].e.g[1]' => '6b', | |
'a.c[1].h' => 7, | |
'a.i' => '8', | |
'j' => 9 | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment