Skip to content

Commit fd3633d

Browse files
committed
Adds automatic detection of Model::Entity representations.
1 parent 2d7b78d commit fd3633d

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

README.markdown

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,32 @@ module API
629629
end
630630
```
631631

632+
### Entity Organization
633+
634+
In addition to separately organizing entities, it may be useful to
635+
put them as namespaced classes underneath the model they represent.
636+
For example:
637+
638+
```ruby
639+
class User
640+
def entity
641+
Entity.new(self)
642+
end
643+
644+
class Entity < Grape::Entity
645+
expose :name, :email
646+
end
647+
end
648+
```
649+
650+
If you organize your entities this way, Grape will automatically
651+
detect the `Entity` class and use it to present your models. In
652+
this example, if you added `present User.new` to your endpoint,
653+
Grape would automatically detect that there is a `User::Entity`
654+
class and use that as the representative entity. This can still
655+
be overridden by using the `:with` option or an explicit
656+
`represents` call.
657+
632658
### Caveats
633659

634660
Entities with duplicate exposure names and conditions will silently overwrite one another.

lib/grape/endpoint.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,8 @@ def present(object, options = {})
255255
entity_class ||= (settings[:representations] || {})[potential]
256256
end
257257

258+
entity_class ||= object.class.const_get(:Entity) if object.class.const_defined?(:Entity)
259+
258260
root = options.delete(:root)
259261

260262
representation = if entity_class

spec/grape/endpoint_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,20 @@ def memoized
347347
last_response.body.should == 'Hiya'
348348
end
349349

350+
it 'should automatically use Klass::Entity if that exists' do
351+
some_model = Class.new
352+
entity = Class.new(Grape::Entity)
353+
entity.stub!(:represent).and_return("Auto-detect!")
354+
355+
some_model.const_set :Entity, entity
356+
357+
subject.get '/example' do
358+
present some_model.new
359+
end
360+
get '/example'
361+
last_response.body.should == 'Auto-detect!'
362+
end
363+
350364
it 'should add a root key to the output if one is given' do
351365
subject.get '/example' do
352366
present({:abc => 'def'}, :root => :root)

0 commit comments

Comments
 (0)