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 a check to Entity#serializable_hash to verify an entity exists on a model #203

Merged
merged 1 commit into from
Jul 17, 2012
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
4 changes: 4 additions & 0 deletions CHANGELOG.markdown
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
0.2.2
=================
* [#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).

0.2.1 (7/11/2012)
=================

Expand Down
5 changes: 4 additions & 1 deletion lib/grape/entity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,10 @@ def serializable_hash(runtime_options = {})
return nil if object.nil?
opts = options.merge(runtime_options || {})
exposures.inject({}) do |output, (attribute, exposure_options)|
output[key_for(attribute)] = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
if object.respond_to?(attribute) && conditions_met?(exposure_options, opts)
output[key_for(attribute)] = value_for(attribute, opts)
end

output
end
end
Expand Down
25 changes: 25 additions & 0 deletions spec/grape/entity_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,31 @@
fresh_class.expose :name
expect{ fresh_class.new(nil).serializable_hash }.not_to raise_error
end

it 'should not throw an exception when an attribute is not found on the object' do
fresh_class.expose :name, :non_existant_attribute
expect{ fresh_class.new(model).serializable_hash }.not_to raise_error
end

it "should not expose attributes that don't exist on the object" do
fresh_class.expose :email, :non_existant_attribute, :name

res = fresh_class.new(model).serializable_hash
res.should have_key :email
res.should_not have_key :non_existant_attribute
res.should have_key :name
end

it "should not expose attributes that don't exist on the object, even with criteria" do
fresh_class.expose :email
fresh_class.expose :non_existant_attribute, :if => lambda { false }
fresh_class.expose :non_existant_attribute2, :if => lambda { true }

res = fresh_class.new(model).serializable_hash
res.should have_key :email
res.should_not have_key :non_existant_attribute
res.should_not have_key :non_existant_attribute2
end
end

describe '#value_for' do
Expand Down