Skip to content

Commit

Permalink
Add support for calling Hash methods on ObjectifiedHash object
Browse files Browse the repository at this point in the history
Fixes #574
  • Loading branch information
NARKOZ committed Jul 12, 2020
1 parent f2910fa commit 242cf2d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/gitlab/objectified_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@ def [](key)

# Respond to messages for which `self.data` has a key
def method_missing(method_name, *args, &block)
data.key?(method_name.to_s) ? data[method_name.to_s] : super
if data.key?(method_name.to_s)
data[method_name.to_s]
elsif data.respond_to?(method_name)
warn 'WARNING: Please convert ObjectifiedHash object to hash before calling Hash methods on it.'
data.send(method_name, *args, &block)
else
super
end
end

def respond_to_missing?(method_name, include_private = false)
Expand Down
15 changes: 15 additions & 0 deletions spec/gitlab/objectified_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@
@oh = described_class.new @hash
end

describe 'Hash behavior' do
let(:hash) { { foo: 'bar' } }
let(:oh) { described_class.new(hash) }

it 'allows to call Hash methods' do
expect(oh.dig('foo')).to eq('bar')
expect(oh.merge(key: :value)).to eq({ 'foo' => 'bar', key: :value })
end

it 'warns about calling Hash methods' do
output = capture_output { oh.values }
expect(output).to eq("WARNING: Please convert ObjectifiedHash object to hash before calling Hash methods on it.\n")
end
end

it 'objectifies a hash' do
expect(@oh.a).to eq(@hash[:a])
expect(@oh.b).to eq(@hash[:b])
Expand Down

0 comments on commit 242cf2d

Please sign in to comment.