Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for nested arrays on ObjectifiedHash (take 2) #570

Merged
merged 5 commits into from
Jul 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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