Skip to content

Commit 1ef1a1f

Browse files
committed
Merge pull request ruby-grape#203 from adamgotterer/master
Add a check to Entity#serializable_hash to verify an entity exists on a model
2 parents 20b5321 + dbb7587 commit 1ef1a1f

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

CHANGELOG.markdown

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
0.2.2
2+
=================
3+
* [#203](https://github.com/intridea/grape/pull/203): Added a check to Entity#serializable_hash that verifies an entity exists on an object - [@adamgotterer](https://github.com/adamgotterer).
4+
15
0.2.1 (7/11/2012)
26
=================
37

lib/grape/entity.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,10 @@ def serializable_hash(runtime_options = {})
259259
return nil if object.nil?
260260
opts = options.merge(runtime_options || {})
261261
exposures.inject({}) do |output, (attribute, exposure_options)|
262-
output[key_for(attribute)] = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
262+
if object.respond_to?(attribute) && conditions_met?(exposure_options, opts)
263+
output[key_for(attribute)] = value_for(attribute, opts)
264+
end
265+
263266
output
264267
end
265268
end

spec/grape/entity_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,31 @@
257257
fresh_class.expose :name
258258
expect{ fresh_class.new(nil).serializable_hash }.not_to raise_error
259259
end
260+
261+
it 'should not throw an exception when an attribute is not found on the object' do
262+
fresh_class.expose :name, :non_existant_attribute
263+
expect{ fresh_class.new(model).serializable_hash }.not_to raise_error
264+
end
265+
266+
it "should not expose attributes that don't exist on the object" do
267+
fresh_class.expose :email, :non_existant_attribute, :name
268+
269+
res = fresh_class.new(model).serializable_hash
270+
res.should have_key :email
271+
res.should_not have_key :non_existant_attribute
272+
res.should have_key :name
273+
end
274+
275+
it "should not expose attributes that don't exist on the object, even with criteria" do
276+
fresh_class.expose :email
277+
fresh_class.expose :non_existant_attribute, :if => lambda { false }
278+
fresh_class.expose :non_existant_attribute2, :if => lambda { true }
279+
280+
res = fresh_class.new(model).serializable_hash
281+
res.should have_key :email
282+
res.should_not have_key :non_existant_attribute
283+
res.should_not have_key :non_existant_attribute2
284+
end
260285
end
261286

262287
describe '#value_for' do

0 commit comments

Comments
 (0)