Skip to content

Commit 90ec8d5

Browse files
author
Declan McGrath
committed
More user friendly docs for context.
1 parent 7130207 commit 90ec8d5

1 file changed

Lines changed: 23 additions & 20 deletions

File tree

README.md

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ backed by ActiveRecord models or by custom objects.
2121
* [Usage] (#usage)
2222
* [Resources] (#resources)
2323
* [JSONAPI::Resource] (#jsonapiresource)
24+
* [Context] (#context)
2425
* [Attributes] (#attributes)
2526
* [Primary Key] (#primary-key)
2627
* [Model Name] (#model-name)
@@ -155,6 +156,28 @@ In the above example vehicles are immutable. A call to `/vehicles` or `/vehicles
155156
of either `car` or `boat`. But calls to PUT or POST a `car` must be made to `/cars`. The rails models backing the above
156157
code use Single Table Inheritance.
157158

159+
#### Context
160+
161+
Sometimes you will want to access things such as the current logged in user (and other state only available within your controllers) from within your resource classes. To make this state available to a resource class you need to put it into the context hash - this can be done via a `context` method one of your controllers or across all controllers using ApplicationController.
162+
163+
For example:
164+
165+
```ruby
166+
class ApplicationController < JSONAPI::ResourceController
167+
def context
168+
{current_user: current_user}
169+
end
170+
end
171+
172+
# Specific resource controllers derive from ApplicationController
173+
# and share its context
174+
class PeopleController < ApplicationController
175+
176+
end
177+
```
178+
179+
You can put things that affect serialization and resource configuration into the context.
180+
158181
#### Attributes
159182

160183
Any of a resource's attributes that are accessible must be explicitly declared. Single attributes can be declared using
@@ -1135,26 +1158,6 @@ A jsonapi-controller generator is avaliable
11351158
rails generate jsonapi:controller contact
11361159
```
11371160
1138-
###### Context
1139-
1140-
The context that's used for serialization and resource configuration is set by the controller's `context` method.
1141-
1142-
For example:
1143-
1144-
```ruby
1145-
class ApplicationController < JSONAPI::ResourceController
1146-
def context
1147-
{current_user: current_user}
1148-
end
1149-
end
1150-
1151-
# Specific resource controllers derive from ApplicationController
1152-
# and share its context
1153-
class PeopleController < ApplicationController
1154-
1155-
end
1156-
```
1157-
11581161
###### Serialization Options
11591162
11601163
Additional options can be passed to the serializer using the `serialization_options` method.

0 commit comments

Comments
 (0)