Skip to content

Commit

Permalink
Add support for nested arrays on ObjectifiedHash (#570)
Browse files Browse the repository at this point in the history
At the moment ObjectifiedHash is missing out on hierarchies of objects where there are hashes contained within an array. Which is annoying as it happens in a lot of API calls.

This just adds an extra step to the initialiser of ObjectifiedHash so that arrays of hashes are handled properly
  • Loading branch information
fabio-gallonetto authored Jul 2, 2020
1 parent aec9423 commit 9931b61
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/gitlab/objectified_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ def initialize(hash)
@hash = hash
@data = hash.each_with_object({}) do |(key, value), data|
value = self.class.new(value) if value.is_a? Hash
value = value.map { |v| v.is_a?(Hash) ? self.class.new(v) : v } if value.is_a? Array
data[key.to_s] = value
end
end
Expand All @@ -23,6 +24,10 @@ def inspect
"#<#{self.class}:#{object_id} {hash: #{hash.inspect}}"
end

def [](key)
data[key]
end

private

attr_reader :hash, :data
Expand Down
13 changes: 12 additions & 1 deletion spec/gitlab/objectified_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

describe Gitlab::ObjectifiedHash do
before do
@hash = { a: 1, b: 2, 'string' => 'string', symbol: :symbol }
@hash = { a: 1, b: 2, 'string' => 'string', symbol: :symbol, array: ['string', { a: 1, b: 2 }] }
@oh = described_class.new @hash
end

Expand All @@ -13,6 +13,17 @@
expect(@oh.b).to eq(@hash[:b])
end

it 'objectifies a hash contained in an array' do
expect(@oh.array[1].a).to eq(@hash[:array][1][:a])
expect(@oh.array[1].b).to eq(@hash[:array][1][:b])
expect(@oh.array[0]).to eq(@hash[:array][0])
end

it 'supports legacy addressing mode' do
expect(@oh['a']).to eq(@hash[:a])
expect(@oh['b']).to eq(@hash[:b])
end

describe '#to_hash' do
it 'returns an original hash' do
expect(@oh.to_hash).to eq(@hash)
Expand Down

0 comments on commit 9931b61

Please sign in to comment.