Skip to content

Commit a779671

Browse files
committed
Merge pull request #631 from theirishpenguin/penguin/320-more-user-friendly-docs-for-context
More user friendly docs for context
2 parents 9e7d68d + 8d32fcf commit a779671

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)
@@ -160,6 +161,28 @@ In the above example vehicles are immutable. A call to `/vehicles` or `/vehicles
160161
of either `car` or `boat`. But calls to PUT or POST a `car` must be made to `/cars`. The rails models backing the above
161162
code use Single Table Inheritance.
162163

164+
#### Context
165+
166+
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 on one of your controllers or across all controllers using ApplicationController.
167+
168+
For example:
169+
170+
```ruby
171+
class ApplicationController < JSONAPI::ResourceController
172+
def context
173+
{current_user: current_user}
174+
end
175+
end
176+
177+
# Specific resource controllers derive from ApplicationController
178+
# and share its context
179+
class PeopleController < ApplicationController
180+
181+
end
182+
```
183+
184+
You can put things that affect serialization and resource configuration into the context.
185+
163186
#### Attributes
164187

165188
Any of a resource's attributes that are accessible must be explicitly declared. Single attributes can be declared using
@@ -1140,26 +1163,6 @@ A jsonapi-controller generator is avaliable
11401163
rails generate jsonapi:controller contact
11411164
```
11421165
1143-
###### Context
1144-
1145-
The context that's used for serialization and resource configuration is set by the controller's `context` method.
1146-
1147-
For example:
1148-
1149-
```ruby
1150-
class ApplicationController < JSONAPI::ResourceController
1151-
def context
1152-
{current_user: current_user}
1153-
end
1154-
end
1155-
1156-
# Specific resource controllers derive from ApplicationController
1157-
# and share its context
1158-
class PeopleController < ApplicationController
1159-
1160-
end
1161-
```
1162-
11631166
###### Serialization Options
11641167
11651168
Additional options can be passed to the serializer using the `serialization_options` method.

0 commit comments

Comments
 (0)