From c9f4864a65891f800f6854bf25100f5cf0a8d5db Mon Sep 17 00:00:00 2001 From: Victor Costan Date: Thu, 7 Aug 2014 02:44:45 -0400 Subject: [PATCH] Fix BurstStruct's respond_to? for string keys. The custom struct implementation handles string/symbol keys correctly in method_missing, but not in respond_to?. This change reuses the (already factored out) code used by method_missing to implement a has_key? method, and uses that method in respond_to?. --- lib/yelp/burst_struct.rb | 6 +++++- spec/yelp/burst_struct_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/yelp/burst_struct.rb b/lib/yelp/burst_struct.rb index 25b7c64..51bc131 100644 --- a/lib/yelp/burst_struct.rb +++ b/lib/yelp/burst_struct.rb @@ -15,7 +15,7 @@ def method_missing(method_name, *arguments, &block) end def respond_to?(method_name, include_private = false) - @hash.keys.include?(method_name) || super + has_key?(method_name) || super end def self.convert_array(array) @@ -35,6 +35,10 @@ def to_json(options = {}) JSON.generate(@hash) end + def has_key?(method_name) + !find_key(method_name).nil? + end + private def return_or_build_struct(method_name) diff --git a/spec/yelp/burst_struct_spec.rb b/spec/yelp/burst_struct_spec.rb index b902b1a..677ea1e 100644 --- a/spec/yelp/burst_struct_spec.rb +++ b/spec/yelp/burst_struct_spec.rb @@ -8,12 +8,20 @@ it 'should return' do expect(struct.foo).to eql 'bar' end + + it { should have_key(:foo) } + it { should have_key('foo') } + + it { should respond_to(:foo) } end context 'when a key does not exist' do it 'should not respond to it' do expect(struct.respond_to? :super_foo).to eql false end + + it { should_not have_key(:super_foo) } + it { should_not have_key('super_foo') } end end @@ -121,4 +129,19 @@ expect(struct.to_json).to eql hash.to_json end end + + context 'struct with string keys' do + subject(:struct) { BurstStruct::Burst.new('foo' => 'bar') } + + context 'when a key exists' do + it 'should return' do + expect(struct.foo).to eql 'bar' + end + + it { should have_key(:foo) } + it { should have_key('foo') } + + it { should respond_to(:foo) } + end + end end