Skip to content

Commit

Permalink
Added dictionary hash extension
Browse files Browse the repository at this point in the history
  • Loading branch information
gabynaiman committed Sep 20, 2013
1 parent 7cf8875 commit d953e40
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
13 changes: 13 additions & 0 deletions lib/core_extended/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ class Hash

Inflector = Struct.new :method, :arguments

def dictionary(parent_key=nil)
Hash.new.tap do |hash|
each do |k,v|
key = [parent_key, k].compact.join('.')
if v.is_a? Hash
hash.merge! v.dictionary(key)
else
hash[key] = v
end
end
end
end

def self.inflectors
@inflectors ||= []
end
Expand Down
2 changes: 1 addition & 1 deletion lib/core_extended/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module CoreExtended
VERSION = '0.0.6'
VERSION = '0.0.7'
end
33 changes: 33 additions & 0 deletions spec/hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,37 @@

end

describe 'Dictionary' do

it 'Simple hash' do
hash = {key_1: 1, 'key_2' => 'text', key_3: []}
hash.dictionary.must_equal 'key_1' => 1,
'key_2' => 'text',
'key_3' => []
end

it 'Nested hashes' do
hash = {
key_1: 1,
'key_2' => 'text',
key_3: [],
key_4: {
1 => '4.1',
2 => {
1 => '4.2.1',
2 => '4.2.2'
}
}
}

hash.dictionary.must_equal 'key_1' => 1,
'key_2' => 'text',
'key_3' => [],
'key_4.1' => '4.1',
'key_4.2.1' => '4.2.1',
'key_4.2.2' => '4.2.2'
end

end

end

0 comments on commit d953e40

Please sign in to comment.