File tree Expand file tree Collapse file tree 2 files changed +32
-10
lines changed
Expand file tree Collapse file tree 2 files changed +32
-10
lines changed Original file line number Diff line number Diff line change @@ -75,6 +75,38 @@ And would respond to the following routes:
7575
7676Serialization takes place automatically. For more detailed usage information, please visit the [ Grape Wiki] ( http://github.com/intridea/grape/wiki ) .
7777
78+ ## Working with Entities
79+
80+ A common problem in designing Ruby APIs is that you probably don't want
81+ the exact structure of your data models exposed. ActiveRecord, for
82+ instance, will dump all of its attributes. While you can override
83+ ` #as_json ` to alter this behavior somewhat, what is really needed is an
84+ intermediary layer between the model and the API. This is where the
85+ ` Grape::Entity ` class comes in.
86+
87+ ``` ruby
88+ module Entities
89+ class User < Grape ::Entity
90+ expose :first_name , :last_name
91+ expose :email , :if => {:authenticated => true }
92+ expose :name , :id => {:version => ' v1' } # deprecated
93+ end
94+ end
95+
96+ class API < Grape ::API
97+ version ' v1' , ' v2'
98+
99+ get ' /users/:id' do
100+ present User .find(params[:id ]),
101+ :with => Entities ::User ,
102+ :authenticated => env.key?(' api.token' )
103+ end
104+ end
105+ ```
106+
107+ For more information about Entities, view the project's YARD
108+ documentation.
109+
78110## Raising Errors
79111
80112You can raise errors explicitly.
Original file line number Diff line number Diff line change @@ -137,16 +137,6 @@ def memoized
137137 end
138138 get '/example'
139139 end
140-
141- it 'should embed version and env when calling through to an entity' do
142- subject . version 'v2'
143- subject . get '/example' do
144- entity_mock = Object . new
145- entity_mock . should_receive ( :represent ) . with ( :version => 'v2' , :env => env )
146- present Object . new , :with => entity_mock
147- end
148- get '/example'
149- end
150140 end
151141
152142 context 'filters' do
You can’t perform that action at this time.
0 commit comments