jsonapi-serializer 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f9205acf76e6255c2007561530f51eb99f45e8c05fc4e588fcd668870726f383
4
+ data.tar.gz: 7e43c43899c6cfbd8655754bcd709cc6a5ef640bc50cde5e8791b5435c49f7de
5
+ SHA512:
6
+ metadata.gz: 40391e6455a9b08ac6ae8790c1623cfb548e31718bf677a0c053943e683f6bd850ebac56ea48fd665eef8f0c246ba182a4e34f962f866e2ee9c3e7883453ff59
7
+ data.tar.gz: ac99a83e5730734b80022c482cf0afe72d98081381eec7122d29ffe4e4303682f48dbdca31e46d8396a98dac779c87f135b9350b2abdc8980ffcb6d9d8614f69
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,668 @@
1
+ # JSON:API Serialization Library
2
+
3
+ A fast [JSON:API](http://jsonapi.org/) serializer for Ruby Objects.
4
+
5
+ Previously this project was called **fast_jsonapi**, we forked the project
6
+ and renamed it to **jsonapi/serializer** in order to keep it alive.
7
+
8
+ We would like to thank the Netflix team for the initial work and to all our
9
+ contributors and users for the continuous support!
10
+
11
+ # Performance Comparison
12
+
13
+ We compare serialization times with `ActiveModelSerializer` and alternative
14
+ implementations as part of performance tests available at
15
+ [jsonapi-serializer/comparisons](https://github.com/jsonapi-serializer/comparisons).
16
+
17
+ We want to ensure that with every
18
+ change on this library, serialization time stays significantly faster than
19
+ the performance provided by the alternatives. Please read the performance
20
+ article in the `docs` folder for any questions related to methodology.
21
+
22
+ # Table of Contents
23
+
24
+ * [Features](#features)
25
+ * [Installation](#installation)
26
+ * [Usage](#usage)
27
+ * [Rails Generator](#rails-generator)
28
+ * [Model Definition](#model-definition)
29
+ * [Serializer Definition](#serializer-definition)
30
+ * [Object Serialization](#object-serialization)
31
+ * [Compound Document](#compound-document)
32
+ * [Key Transforms](#key-transforms)
33
+ * [Collection Serialization](#collection-serialization)
34
+ * [Caching](#caching)
35
+ * [Params](#params)
36
+ * [Conditional Attributes](#conditional-attributes)
37
+ * [Conditional Relationships](#conditional-relationships)
38
+ * [Specifying a Relationship Serializer](#specifying-a-relationship-serializer)
39
+ * [Sparse Fieldsets](#sparse-fieldsets)
40
+ * [Using helper methods](#using-helper-methods)
41
+ * [Contributing](#contributing)
42
+
43
+
44
+ ## Features
45
+
46
+ * Declaration syntax similar to Active Model Serializer
47
+ * Support for `belongs_to`, `has_many` and `has_one`
48
+ * Support for compound documents (included)
49
+ * Optimized serialization of compound documents
50
+ * Caching
51
+
52
+ ## Installation
53
+
54
+ Add this line to your application's Gemfile:
55
+
56
+ ```ruby
57
+ gem 'jsonapi-serializer'
58
+ ```
59
+
60
+ Execute:
61
+
62
+ ```bash
63
+ $ bundle install
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ ### Rails Generator
69
+ You can use the bundled generator if you are using the library inside of
70
+ a Rails project:
71
+
72
+ rails g serializer Movie name year
73
+
74
+ This will create a new serializer in `app/serializers/movie_serializer.rb`
75
+
76
+ ### Model Definition
77
+
78
+ ```ruby
79
+ class Movie
80
+ attr_accessor :id, :name, :year, :actor_ids, :owner_id, :movie_type_id
81
+ end
82
+ ```
83
+
84
+ ### Serializer Definition
85
+
86
+ ```ruby
87
+ class MovieSerializer
88
+ include JSONAPI::Serializer
89
+
90
+ set_type :movie # optional
91
+ set_id :owner_id # optional
92
+ attributes :name, :year
93
+ has_many :actors
94
+ belongs_to :owner, record_type: :user
95
+ belongs_to :movie_type
96
+ end
97
+ ```
98
+
99
+ ### Sample Object
100
+
101
+ ```ruby
102
+ movie = Movie.new
103
+ movie.id = 232
104
+ movie.name = 'test movie'
105
+ movie.actor_ids = [1, 2, 3]
106
+ movie.owner_id = 3
107
+ movie.movie_type_id = 1
108
+ movie
109
+
110
+ movies =
111
+ 2.times.map do |i|
112
+ m = Movie.new
113
+ m.id = i + 1
114
+ m.name = "test movie #{i}"
115
+ m.actor_ids = [1, 2, 3]
116
+ m.owner_id = 3
117
+ m.movie_type_id = 1
118
+ m
119
+ end
120
+ ```
121
+
122
+ ### Object Serialization
123
+
124
+ #### Return a hash
125
+ ```ruby
126
+ hash = MovieSerializer.new(movie).serializable_hash
127
+ ```
128
+
129
+ #### Return Serialized JSON
130
+ ```ruby
131
+ json_string = MovieSerializer.new(movie).serializable_hash.to_json
132
+ ```
133
+
134
+ #### Serialized Output
135
+
136
+ ```json
137
+ {
138
+ "data": {
139
+ "id": "3",
140
+ "type": "movie",
141
+ "attributes": {
142
+ "name": "test movie",
143
+ "year": null
144
+ },
145
+ "relationships": {
146
+ "actors": {
147
+ "data": [
148
+ {
149
+ "id": "1",
150
+ "type": "actor"
151
+ },
152
+ {
153
+ "id": "2",
154
+ "type": "actor"
155
+ }
156
+ ]
157
+ },
158
+ "owner": {
159
+ "data": {
160
+ "id": "3",
161
+ "type": "user"
162
+ }
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ ```
169
+
170
+ #### The Optionality of `set_type`
171
+ By default fast_jsonapi will try to figure the type based on the name of the serializer class. For example `class MovieSerializer` will automatically have a type of `:movie`. If your serializer class name does not follow this format, you have to manually state the `set_type` at the serializer.
172
+
173
+ ### Key Transforms
174
+ By default fast_jsonapi underscores the key names. It supports the same key transforms that are supported by AMS. Here is the syntax of specifying a key transform
175
+
176
+ ```ruby
177
+ class MovieSerializer
178
+ include JSONAPI::Serializer
179
+
180
+ # Available options :camel, :camel_lower, :dash, :underscore(default)
181
+ set_key_transform :camel
182
+ end
183
+ ```
184
+ Here are examples of how these options transform the keys
185
+
186
+ ```ruby
187
+ set_key_transform :camel # "some_key" => "SomeKey"
188
+ set_key_transform :camel_lower # "some_key" => "someKey"
189
+ set_key_transform :dash # "some_key" => "some-key"
190
+ set_key_transform :underscore # "some_key" => "some_key"
191
+ ```
192
+
193
+ ### Attributes
194
+ Attributes are defined using the `attributes` method. This method is also aliased as `attribute`, which is useful when defining a single attribute.
195
+
196
+ By default, attributes are read directly from the model property of the same name. In this example, `name` is expected to be a property of the object being serialized:
197
+
198
+ ```ruby
199
+ class MovieSerializer
200
+ include JSONAPI::Serializer
201
+
202
+ attribute :name
203
+ end
204
+ ```
205
+
206
+ Custom attributes that must be serialized but do not exist on the model can be declared using Ruby block syntax:
207
+
208
+ ```ruby
209
+ class MovieSerializer
210
+ include JSONAPI::Serializer
211
+
212
+ attributes :name, :year
213
+
214
+ attribute :name_with_year do |object|
215
+ "#{object.name} (#{object.year})"
216
+ end
217
+ end
218
+ ```
219
+
220
+ The block syntax can also be used to override the property on the object:
221
+
222
+ ```ruby
223
+ class MovieSerializer
224
+ include JSONAPI::Serializer
225
+
226
+ attribute :name do |object|
227
+ "#{object.name} Part 2"
228
+ end
229
+ end
230
+ ```
231
+
232
+ Attributes can also use a different name by passing the original method or accessor with a proc shortcut:
233
+
234
+ ```ruby
235
+ class MovieSerializer
236
+ include JSONAPI::Serializer
237
+
238
+ attributes :name
239
+
240
+ attribute :released_in_year, &:year
241
+ end
242
+ ```
243
+
244
+ ### Links Per Object
245
+ Links are defined using the `link` method. By default, links are read directly from the model property of the same name. In this example, `public_url` is expected to be a property of the object being serialized.
246
+
247
+ You can configure the method to use on the object for example a link with key `self` will get set to the value returned by a method called `url` on the movie object.
248
+
249
+ You can also use a block to define a url as shown in `custom_url`. You can access params in these blocks as well as shown in `personalized_url`
250
+
251
+ ```ruby
252
+ class MovieSerializer
253
+ include JSONAPI::Serializer
254
+
255
+ link :public_url
256
+
257
+ link :self, :url
258
+
259
+ link :custom_url do |object|
260
+ "http://movies.com/#{object.name}-(#{object.year})"
261
+ end
262
+
263
+ link :personalized_url do |object, params|
264
+ "http://movies.com/#{object.name}-#{params[:user].reference_code}"
265
+ end
266
+ end
267
+ ```
268
+
269
+ #### Links on a Relationship
270
+
271
+ You can specify [relationship links](http://jsonapi.org/format/#document-resource-object-relationships) by using the `links:` option on the serializer. Relationship links in JSON API are useful if you want to load a parent document and then load associated documents later due to size constraints (see [related resource links](http://jsonapi.org/format/#document-resource-object-related-resource-links))
272
+
273
+ ```ruby
274
+ class MovieSerializer
275
+ include JSONAPI::Serializer
276
+
277
+ has_many :actors, links: {
278
+ self: :url,
279
+ related: -> (object) {
280
+ "https://movies.com/#{object.id}/actors"
281
+ }
282
+ }
283
+ end
284
+ ```
285
+
286
+ Relationship links can also be configured to be defined as a method on the object.
287
+
288
+ ```ruby
289
+ has_many :actors, links: :actor_relationship_links
290
+ ```
291
+
292
+ This will create a `self` reference for the relationship, and a `related` link for loading the actors relationship later. NB: This will not automatically disable loading the data in the relationship, you'll need to do that using the `lazy_load_data` option:
293
+
294
+ ```ruby
295
+ has_many :actors, lazy_load_data: true, links: {
296
+ self: :url,
297
+ related: -> (object) {
298
+ "https://movies.com/#{object.id}/actors"
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### Meta Per Resource
304
+
305
+ For every resource in the collection, you can include a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.
306
+
307
+
308
+ ```ruby
309
+ class MovieSerializer
310
+ include JSONAPI::Serializer
311
+
312
+ meta do |movie|
313
+ {
314
+ years_since_release: Date.current.year - movie.year
315
+ }
316
+ end
317
+ end
318
+ ```
319
+
320
+ ### Compound Document
321
+
322
+ Support for top-level and nested included associations through `options[:include]`.
323
+
324
+ ```ruby
325
+ options = {}
326
+ options[:meta] = { total: 2 }
327
+ options[:links] = {
328
+ self: '...',
329
+ next: '...',
330
+ prev: '...'
331
+ }
332
+ options[:include] = [:actors, :'actors.agency', :'actors.agency.state']
333
+ MovieSerializer.new(movies, options).serializable_hash.to_json
334
+ ```
335
+
336
+ ### Collection Serialization
337
+
338
+ ```ruby
339
+ options[:meta] = { total: 2 }
340
+ options[:links] = {
341
+ self: '...',
342
+ next: '...',
343
+ prev: '...'
344
+ }
345
+ hash = MovieSerializer.new(movies, options).serializable_hash
346
+ json_string = MovieSerializer.new(movies, options).serializable_hash.to_json
347
+ ```
348
+
349
+ #### Control Over Collection Serialization
350
+
351
+ You can use `is_collection` option to have better control over collection serialization.
352
+
353
+ If this option is not provided or `nil` autodetect logic is used to try understand
354
+ if provided resource is a single object or collection.
355
+
356
+ Autodetect logic is compatible with most DB toolkits (ActiveRecord, Sequel, etc.) but
357
+ **cannot** guarantee that single vs collection will be always detected properly.
358
+
359
+ ```ruby
360
+ options[:is_collection]
361
+ ```
362
+
363
+ was introduced to be able to have precise control this behavior
364
+
365
+ - `nil` or not provided: will try to autodetect single vs collection (please, see notes above)
366
+ - `true` will always treat input resource as *collection*
367
+ - `false` will always treat input resource as *single object*
368
+
369
+ ### Caching
370
+
371
+ To enable caching, use `cache_options store: <cache_store>`:
372
+
373
+ ```ruby
374
+ class MovieSerializer
375
+ include JSONAPI::Serializer
376
+
377
+ # use rails cache with a separate namespace and fixed expiry
378
+ cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 1.hour
379
+ end
380
+ ```
381
+
382
+ `store` is required can be anything that implements a
383
+ `#fetch(record, **options, &block)` method:
384
+
385
+ - `record` is the record that is currently serialized
386
+ - `options` is everything that was passed to `cache_options` except `store`, so it can be everyhing the cache store supports
387
+ - `&block` should be executed to fetch new data if cache is empty
388
+
389
+ So for the example above it will call the cache instance like this:
390
+
391
+ ```ruby
392
+ Rails.cache.fetch(record, namespace: 'jsonapi-serializer', expires_in: 1.hour) { ... }
393
+ ```
394
+
395
+ ### Params
396
+
397
+ In some cases, attribute values might require more information than what is
398
+ available on the record, for example, access privileges or other information
399
+ related to a current authenticated user. The `options[:params]` value covers these
400
+ cases by allowing you to pass in a hash of additional parameters necessary for
401
+ your use case.
402
+
403
+ Leveraging the new params is easy, when you define a custom id, attribute or
404
+ relationship with a block you opt-in to using params by adding it as a block
405
+ parameter.
406
+
407
+ ```ruby
408
+ class MovieSerializer
409
+ include JSONAPI::Serializer
410
+
411
+ set_id do |movie, params|
412
+ # in here, params is a hash containing the `:admin` key
413
+ params[:admin] ? movie.owner_id : "movie-#{movie.id}"
414
+ end
415
+
416
+ attributes :name, :year
417
+ attribute :can_view_early do |movie, params|
418
+ # in here, params is a hash containing the `:current_user` key
419
+ params[:current_user].is_employee? ? true : false
420
+ end
421
+
422
+ belongs_to :primary_agent do |movie, params|
423
+ # in here, params is a hash containing the `:current_user` key
424
+ params[:current_user].is_employee? ? true : false
425
+ end
426
+ end
427
+
428
+ # ...
429
+ current_user = User.find(cookies[:current_user_id])
430
+ serializer = MovieSerializer.new(movie, {params: {current_user: current_user}})
431
+ serializer.serializable_hash
432
+ ```
433
+
434
+ Custom attributes and relationships that only receive the resource are still possible by defining
435
+ the block to only receive one argument.
436
+
437
+ ### Conditional Attributes
438
+
439
+ Conditional attributes can be defined by passing a Proc to the `if` key on the `attribute` method. Return `true` if the attribute should be serialized, and `false` if not. The record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.
440
+
441
+ ```ruby
442
+ class MovieSerializer
443
+ include JSONAPI::Serializer
444
+
445
+ attributes :name, :year
446
+ attribute :release_year, if: Proc.new { |record|
447
+ # Release year will only be serialized if it's greater than 1990
448
+ record.release_year > 1990
449
+ }
450
+
451
+ attribute :director, if: Proc.new { |record, params|
452
+ # The director will be serialized only if the :admin key of params is true
453
+ params && params[:admin] == true
454
+ }
455
+ end
456
+
457
+ # ...
458
+ current_user = User.find(cookies[:current_user_id])
459
+ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
460
+ serializer.serializable_hash
461
+ ```
462
+
463
+ ### Conditional Relationships
464
+
465
+ Conditional relationships can be defined by passing a Proc to the `if` key. Return `true` if the relationship should be serialized, and `false` if not. The record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.
466
+
467
+ ```ruby
468
+ class MovieSerializer
469
+ include JSONAPI::Serializer
470
+
471
+ # Actors will only be serialized if the record has any associated actors
472
+ has_many :actors, if: Proc.new { |record| record.actors.any? }
473
+
474
+ # Owner will only be serialized if the :admin key of params is true
475
+ belongs_to :owner, if: Proc.new { |record, params| params && params[:admin] == true }
476
+ end
477
+
478
+ # ...
479
+ current_user = User.find(cookies[:current_user_id])
480
+ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
481
+ serializer.serializable_hash
482
+ ```
483
+
484
+ ### Specifying a Relationship Serializer
485
+
486
+ In many cases, the relationship can automatically detect the serializer to use.
487
+
488
+ ```ruby
489
+ class MovieSerializer
490
+ include JSONAPI::Serializer
491
+
492
+ # resolves to StudioSerializer
493
+ belongs_to :studio
494
+ # resolves to ActorSerializer
495
+ has_many :actors
496
+ end
497
+ ```
498
+
499
+ At other times, such as when a property name differs from the class name, you may need to explicitly state the serializer to use. You can do so by specifying a different symbol or the serializer class itself (which is the recommended usage):
500
+
501
+ ```ruby
502
+ class MovieSerializer
503
+ include JSONAPI::Serializer
504
+
505
+ # resolves to MovieStudioSerializer
506
+ belongs_to :studio, serializer: :movie_studio
507
+ # resolves to PerformerSerializer
508
+ has_many :actors, serializer: PerformerSerializer
509
+ end
510
+ ```
511
+
512
+ For more advanced cases, such as polymorphic relationships and Single Table Inheritance, you may need even greater control to select the serializer based on the specific object or some specified serialization parameters. You can do by defining the serializer as a `Proc`:
513
+
514
+ ```ruby
515
+ class MovieSerializer
516
+ include JSONAPI::Serializer
517
+
518
+ has_many :actors, serializer: Proc.new do |record, params|
519
+ if record.comedian?
520
+ ComedianSerializer
521
+ elsif params[:use_drama_serializer]
522
+ DramaSerializer
523
+ else
524
+ ActorSerializer
525
+ end
526
+ end
527
+ end
528
+ ```
529
+
530
+ ### Sparse Fieldsets
531
+
532
+ Attributes and relationships can be selectively returned per record type by using the `fields` option.
533
+
534
+ ```ruby
535
+ class MovieSerializer
536
+ include JSONAPI::Serializer
537
+
538
+ attributes :name, :year
539
+ end
540
+
541
+ serializer = MovieSerializer.new(movie, { fields: { movie: [:name] } })
542
+ serializer.serializable_hash
543
+ ```
544
+
545
+ ### Using helper methods
546
+
547
+ You can mix-in code from another ruby module into your serializer class to reuse functions across your app.
548
+
549
+ Since a serializer is evaluated in a the context of a `class` rather than an `instance` of a class, you need to make sure that your methods act as `class` methods when mixed in.
550
+
551
+
552
+ ##### Using ActiveSupport::Concern
553
+
554
+ ``` ruby
555
+
556
+ module AvatarHelper
557
+ extend ActiveSupport::Concern
558
+
559
+ class_methods do
560
+ def avatar_url(user)
561
+ user.image.url
562
+ end
563
+ end
564
+ end
565
+
566
+ class UserSerializer
567
+ include JSONAPI::Serializer
568
+
569
+ include AvatarHelper # mixes in your helper method as class method
570
+
571
+ set_type :user
572
+
573
+ attributes :name, :email
574
+
575
+ attribute :avatar do |user|
576
+ avatar_url(user)
577
+ end
578
+ end
579
+
580
+ ```
581
+
582
+ ##### Using Plain Old Ruby
583
+
584
+ ``` ruby
585
+ module AvatarHelper
586
+ def avatar_url(user)
587
+ user.image.url
588
+ end
589
+ end
590
+
591
+ class UserSerializer
592
+ include JSONAPI::Serializer
593
+
594
+ extend AvatarHelper # mixes in your helper method as class method
595
+
596
+ set_type :user
597
+
598
+ attributes :name, :email
599
+
600
+ attribute :avatar do |user|
601
+ avatar_url(user)
602
+ end
603
+ end
604
+
605
+ ```
606
+
607
+ ### Customizable Options
608
+
609
+ Option | Purpose | Example
610
+ ------------ | ------------- | -------------
611
+ set_type | Type name of Object | `set_type :movie`
612
+ key | Key of Object | `belongs_to :owner, key: :user`
613
+ set_id | ID of Object | `set_id :owner_id` or `set_id { \|record, params\| params[:admin] ? record.id : "#{record.name.downcase}-#{record.id}" }`
614
+ cache_options | Hash with store to enable caching and optional further cache options | `cache_options store: ActiveSupport::Cache::MemoryStore.new, expires_in: 5.minutes`
615
+ id_method_name | Set custom method name to get ID of an object (If block is provided for the relationship, `id_method_name` is invoked on the return value of the block instead of the resource object) | `has_many :locations, id_method_name: :place_ids`
616
+ object_method_name | Set custom method name to get related objects | `has_many :locations, object_method_name: :places`
617
+ record_type | Set custom Object Type for a relationship | `belongs_to :owner, record_type: :user`
618
+ serializer | Set custom Serializer for a relationship | `has_many :actors, serializer: :custom_actor`, `has_many :actors, serializer: MyApp::Api::V1::ActorSerializer`, or `has_many :actors, serializer -> (object, params) { (return a serializer class) }`
619
+ polymorphic | Allows different record types for a polymorphic association | `has_many :targets, polymorphic: true`
620
+ polymorphic | Sets custom record types for each object class in a polymorphic association | `has_many :targets, polymorphic: { Person => :person, Group => :group }`
621
+
622
+ ### Instrumentation
623
+
624
+ `fast_jsonapi` also has builtin [Skylight](https://www.skylight.io/) integration. To enable, add the following to an initializer:
625
+
626
+ ```ruby
627
+ require 'fast_jsonapi/instrumentation/skylight'
628
+ ```
629
+
630
+ Skylight relies on `ActiveSupport::Notifications` to track these two core methods. If you would like to use these notifications without using Skylight, simply require the instrumentation integration:
631
+
632
+ ```ruby
633
+ require 'fast_jsonapi/instrumentation'
634
+ ```
635
+
636
+ The two instrumented notifications are supplied by these two constants:
637
+ * `FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION`
638
+ * `FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION`
639
+
640
+ It is also possible to instrument one method without the other by using one of the following require statements:
641
+
642
+ ```ruby
643
+ require 'fast_jsonapi/instrumentation/serializable_hash'
644
+ require 'fast_jsonapi/instrumentation/serialized_json'
645
+ ```
646
+
647
+ Same goes for the Skylight integration:
648
+ ```ruby
649
+ require 'fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash'
650
+ require 'fast_jsonapi/instrumentation/skylight/normalizers/serialized_json'
651
+ ```
652
+
653
+ ### Running Tests
654
+ The project has and requires unit tests, functional tests and performance
655
+ tests. To run tests use the following command:
656
+
657
+ ```bash
658
+ rspec
659
+ ```
660
+
661
+ ## Contributing
662
+
663
+ Please follow the instructions we provide as part of the issue and
664
+ pull request creation processes.
665
+
666
+ This project is intended to be a safe, welcoming space for collaboration, and
667
+ contributors are expected to adhere to the
668
+ [Contributor Covenant](http://contributor-covenant.org) code of conduct.