From 9931b6113d9560064a612bd6a36af20bd00b46fc Mon Sep 17 00:00:00 2001 From: fabio-gallonetto <55149722+fabio-gallonetto@users.noreply.github.com> Date: Thu, 2 Jul 2020 10:20:51 +0100 Subject: [PATCH] Add support for nested arrays on ObjectifiedHash (#570) 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 --- lib/gitlab/objectified_hash.rb | 5 +++++ spec/gitlab/objectified_hash_spec.rb | 13 ++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/gitlab/objectified_hash.rb b/lib/gitlab/objectified_hash.rb index 993fea8e5..2b70632c6 100644 --- a/lib/gitlab/objectified_hash.rb +++ b/lib/gitlab/objectified_hash.rb @@ -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 @@ -23,6 +24,10 @@ def inspect "#<#{self.class}:#{object_id} {hash: #{hash.inspect}}" end + def [](key) + data[key] + end + private attr_reader :hash, :data diff --git a/spec/gitlab/objectified_hash_spec.rb b/spec/gitlab/objectified_hash_spec.rb index 1808a4f2f..6b6d19d7c 100644 --- a/spec/gitlab/objectified_hash_spec.rb +++ b/spec/gitlab/objectified_hash_spec.rb @@ -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 @@ -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)