Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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?.
  • Loading branch information
pwnall authored and Jordan Stephens committed Aug 21, 2014
1 parent d4b4aaa commit c9f4864
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/yelp/burst_struct.rb
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
23 changes: 23 additions & 0 deletions spec/yelp/burst_struct_spec.rb
Expand Up @@ -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

Expand Down Expand Up @@ -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

0 comments on commit c9f4864

Please sign in to comment.