Skip to content

Commit

Permalink
handles all sorts of collections with #present
Browse files Browse the repository at this point in the history
As long as the object responds to #first it can be used as a collection.
Coincidentally, ActiveRecord::Relation does.
  • Loading branch information
Jonas Pfenniger committed Mar 4, 2013
1 parent 945b067 commit b993dd3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/grape/endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def present(object, options = {})
entity_class = options.delete(:with)

# auto-detect the entity from the first object in the collection
object_instance = object.is_a?(Array) ? object.first : object
object_instance = object.respond_to?(:first) ? object.first : object

object_instance.class.ancestors.each do |potential|
entity_class ||= (settings[:representations] || {})[potential]
Expand Down
11 changes: 11 additions & 0 deletions spec/grape/entity_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,24 @@ def app; subject end
entity.stub!(:represent).and_return("Hiya")

class TestObject; end
class FakeCollection
def first; TestObject.new; end
end

subject.represent TestObject, :with => entity
subject.get '/example' do
present [TestObject.new]
end

subject.get '/example2' do
present FakeCollection.new
end

get '/example'
last_response.body.should == "Hiya"

get '/example2'
last_response.body.should == "Hiya"
end

it 'pulls a representation from the class ancestor if it exists' do
Expand Down

0 comments on commit b993dd3

Please sign in to comment.