File tree Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -629,6 +629,32 @@ module API
629
629
end
630
630
```
631
631
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
+
632
658
### Caveats
633
659
634
660
Entities with duplicate exposure names and conditions will silently overwrite one another.
Original file line number Diff line number Diff line change @@ -255,6 +255,8 @@ def present(object, options = {})
255
255
entity_class ||= ( settings [ :representations ] || { } ) [ potential ]
256
256
end
257
257
258
+ entity_class ||= object . class . const_get ( :Entity ) if object . class . const_defined? ( :Entity )
259
+
258
260
root = options . delete ( :root )
259
261
260
262
representation = if entity_class
Original file line number Diff line number Diff line change @@ -347,6 +347,20 @@ def memoized
347
347
last_response . body . should == 'Hiya'
348
348
end
349
349
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
+
350
364
it 'should add a root key to the output if one is given' do
351
365
subject . get '/example' do
352
366
present ( { :abc => 'def' } , :root => :root )
You can’t perform that action at this time.
0 commit comments