at_fast_jsonapi 1.5.1

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: 291694e585eb1b604cf33d0901571df3324b63daa24cb68fdd5c08b767bc2c18
4
+ data.tar.gz: 48101839762d8b07eb20767e7299b558f333aa39b8059fd608fe3da8c8298674
5
+ SHA512:
6
+ metadata.gz: a513199fd7829c20915c6b35ef5bba155ec75b9c9f44460dca519d8b71dda867f278de3ef961fcaf77986bf8c62436f65f757166f8bc5f714f3c6705413c53a9
7
+ data.tar.gz: d5e5ca265e0539ba7e82145245cc7d80bbdd20b086b5308455c713832361d56dd82fbd14e47b5a6662f8c7eb7d68164c884c4fda4d94a03fbe9dbfe910a1f469
@@ -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,581 @@
1
+ # Fast JSON API
2
+
3
+ [![Build Status](https://travis-ci.org/Netflix/fast_jsonapi.svg?branch=master)](https://travis-ci.org/Netflix/fast_jsonapi)
4
+
5
+ A lightning fast [JSON:API](http://jsonapi.org/) serializer for Ruby Objects.
6
+
7
+ # Performance Comparison
8
+
9
+ We compare serialization times with Active Model Serializer as part of RSpec performance tests included on this library. We want to ensure that with every change on this library, serialization time is at least `25 times` faster than Active Model Serializers on up to current benchmark of 1000 records. Please read the [performance document](https://github.com/Netflix/fast_jsonapi/blob/master/performance_methodology.md) for any questions related to methodology.
10
+
11
+ ## Benchmark times for 250 records
12
+
13
+ ```bash
14
+ $ rspec
15
+ Active Model Serializer serialized 250 records in 138.71 ms
16
+ Fast JSON API serialized 250 records in 3.01 ms
17
+ ```
18
+
19
+ # Table of Contents
20
+
21
+ * [Features](#features)
22
+ * [Installation](#installation)
23
+ * [Usage](#usage)
24
+ * [Rails Generator](#rails-generator)
25
+ * [Model Definition](#model-definition)
26
+ * [Serializer Definition](#serializer-definition)
27
+ * [Object Serialization](#object-serialization)
28
+ * [Compound Document](#compound-document)
29
+ * [Key Transforms](#key-transforms)
30
+ * [Collection Serialization](#collection-serialization)
31
+ * [Caching](#caching)
32
+ * [Params](#params)
33
+ * [Conditional Attributes](#conditional-attributes)
34
+ * [Conditional Relationships](#conditional-relationships)
35
+ * [Sparse Fieldsets](#sparse-fieldsets)
36
+ * [Using helper methods](#using-helper-methods)
37
+ * [Contributing](#contributing)
38
+
39
+
40
+ ## Features
41
+
42
+ * Declaration syntax similar to Active Model Serializer
43
+ * Support for `belongs_to`, `has_many` and `has_one`
44
+ * Support for compound documents (included)
45
+ * Optimized serialization of compound documents
46
+ * Caching
47
+
48
+ ## Installation
49
+
50
+ Add this line to your application's Gemfile:
51
+
52
+ ```ruby
53
+ gem 'fast_jsonapi'
54
+ ```
55
+
56
+ Execute:
57
+
58
+ ```bash
59
+ $ bundle install
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ ### Rails Generator
65
+ You can use the bundled generator if you are using the library inside of
66
+ a Rails project:
67
+
68
+ rails g serializer Movie name year
69
+
70
+ This will create a new serializer in `app/serializers/movie_serializer.rb`
71
+
72
+ ### Model Definition
73
+
74
+ ```ruby
75
+ class Movie
76
+ attr_accessor :id, :name, :year, :actor_ids, :owner_id, :movie_type_id
77
+ end
78
+ ```
79
+
80
+ ### Serializer Definition
81
+
82
+ ```ruby
83
+ class MovieSerializer
84
+ include FastJsonapi::ObjectSerializer
85
+ set_type :movie # optional
86
+ set_id :owner_id # optional
87
+ attributes :name, :year
88
+ has_many :actors
89
+ belongs_to :owner, record_type: :user
90
+ belongs_to :movie_type
91
+ end
92
+ ```
93
+
94
+ ### Sample Object
95
+
96
+ ```ruby
97
+ movie = Movie.new
98
+ movie.id = 232
99
+ movie.name = 'test movie'
100
+ movie.actor_ids = [1, 2, 3]
101
+ movie.owner_id = 3
102
+ movie.movie_type_id = 1
103
+ movie
104
+ ```
105
+
106
+ ### Object Serialization
107
+
108
+ #### Return a hash
109
+ ```ruby
110
+ hash = MovieSerializer.new(movie).serializable_hash
111
+ ```
112
+
113
+ #### Return Serialized JSON
114
+ ```ruby
115
+ json_string = MovieSerializer.new(movie).serialized_json
116
+ ```
117
+
118
+ #### Serialized Output
119
+
120
+ ```json
121
+ {
122
+ "data": {
123
+ "id": "3",
124
+ "type": "movie",
125
+ "attributes": {
126
+ "name": "test movie",
127
+ "year": null
128
+ },
129
+ "relationships": {
130
+ "actors": {
131
+ "data": [
132
+ {
133
+ "id": "1",
134
+ "type": "actor"
135
+ },
136
+ {
137
+ "id": "2",
138
+ "type": "actor"
139
+ }
140
+ ]
141
+ },
142
+ "owner": {
143
+ "data": {
144
+ "id": "3",
145
+ "type": "user"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ ```
153
+
154
+ ### Key Transforms
155
+ 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
156
+
157
+ ```ruby
158
+ class MovieSerializer
159
+ include FastJsonapi::ObjectSerializer
160
+ # Available options :camel, :camel_lower, :dash, :underscore(default)
161
+ set_key_transform :camel
162
+ end
163
+ ```
164
+ Here are examples of how these options transform the keys
165
+
166
+ ```ruby
167
+ set_key_transform :camel # "some_key" => "SomeKey"
168
+ set_key_transform :camel_lower # "some_key" => "someKey"
169
+ set_key_transform :dash # "some_key" => "some-key"
170
+ set_key_transform :underscore # "some_key" => "some_key"
171
+ ```
172
+
173
+ ### Attributes
174
+ Attributes are defined in FastJsonapi using the `attributes` method. This method is also aliased as `attribute`, which is useful when defining a single attribute.
175
+
176
+ 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:
177
+
178
+ ```ruby
179
+ class MovieSerializer
180
+ include FastJsonapi::ObjectSerializer
181
+
182
+ attribute :name
183
+ end
184
+ ```
185
+
186
+ Custom attributes that must be serialized but do not exist on the model can be declared using Ruby block syntax:
187
+
188
+ ```ruby
189
+ class MovieSerializer
190
+ include FastJsonapi::ObjectSerializer
191
+
192
+ attributes :name, :year
193
+
194
+ attribute :name_with_year do |object|
195
+ "#{object.name} (#{object.year})"
196
+ end
197
+ end
198
+ ```
199
+
200
+ The block syntax can also be used to override the property on the object:
201
+
202
+ ```ruby
203
+ class MovieSerializer
204
+ include FastJsonapi::ObjectSerializer
205
+
206
+ attribute :name do |object|
207
+ "#{object.name} Part 2"
208
+ end
209
+ end
210
+ ```
211
+
212
+ Attributes can also use a different name by passing the original method or accessor with a proc shortcut:
213
+
214
+ ```ruby
215
+ class MovieSerializer
216
+ include FastJsonapi::ObjectSerializer
217
+
218
+ attributes :name
219
+
220
+ attribute :released_in_year, &:year
221
+ end
222
+ ```
223
+
224
+ ### Links Per Object
225
+ Links are defined in FastJsonapi 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.
226
+
227
+ 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.
228
+
229
+ 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`
230
+
231
+ ```ruby
232
+ class MovieSerializer
233
+ include FastJsonapi::ObjectSerializer
234
+
235
+ link :public_url
236
+
237
+ link :self, :url
238
+
239
+ link :custom_url do |object|
240
+ "http://movies.com/#{object.name}-(#{object.year})"
241
+ end
242
+
243
+ link :personalized_url do |object, params|
244
+ "http://movies.com/#{object.name}-#{params[:user].reference_code}"
245
+ end
246
+ end
247
+ ```
248
+
249
+ #### Links on a Relationship
250
+
251
+ 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))
252
+
253
+ ```ruby
254
+ class MovieSerializer
255
+ include FastJsonapi::ObjectSerializer
256
+
257
+ has_many :actors, links: {
258
+ self: :url,
259
+ related: -> (object) {
260
+ "https://movies.com/#{object.id}/actors"
261
+ }
262
+ }
263
+ end
264
+ ```
265
+
266
+ 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:
267
+
268
+ ```ruby
269
+ has_many :actors, lazy_load_data: true, links: {
270
+ self: :url,
271
+ related: -> (object) {
272
+ "https://movies.com/#{object.id}/actors"
273
+ }
274
+ }
275
+ ```
276
+
277
+ ### Meta Per Resource
278
+
279
+ 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.
280
+
281
+
282
+ ```ruby
283
+ class MovieSerializer
284
+ include FastJsonapi::ObjectSerializer
285
+
286
+ meta do |movie|
287
+ {
288
+ years_since_release: Date.current.year - movie.year
289
+ }
290
+ end
291
+ end
292
+ ```
293
+
294
+ ### Compound Document
295
+
296
+ Support for top-level and nested included associations through ` options[:include] `.
297
+
298
+ ```ruby
299
+ options = {}
300
+ options[:meta] = { total: 2 }
301
+ options[:links] = {
302
+ self: '...',
303
+ next: '...',
304
+ prev: '...'
305
+ }
306
+ options[:include] = [:actors, :'actors.agency', :'actors.agency.state']
307
+ MovieSerializer.new([movie, movie], options).serialized_json
308
+ ```
309
+
310
+ ### Collection Serialization
311
+
312
+ ```ruby
313
+ options[:meta] = { total: 2 }
314
+ options[:links] = {
315
+ self: '...',
316
+ next: '...',
317
+ prev: '...'
318
+ }
319
+ hash = MovieSerializer.new([movie, movie], options).serializable_hash
320
+ json_string = MovieSerializer.new([movie, movie], options).serialized_json
321
+ ```
322
+
323
+ #### Control Over Collection Serialization
324
+
325
+ You can use `is_collection` option to have better control over collection serialization.
326
+
327
+ If this option is not provided or `nil` autedetect logic is used to try understand
328
+ if provided resource is a single object or collection.
329
+
330
+ Autodetect logic is compatible with most DB toolkits (ActiveRecord, Sequel, etc.) but
331
+ **cannot** guarantee that single vs collection will be always detected properly.
332
+
333
+ ```ruby
334
+ options[:is_collection]
335
+ ```
336
+
337
+ was introduced to be able to have precise control this behavior
338
+
339
+ - `nil` or not provided: will try to autodetect single vs collection (please, see notes above)
340
+ - `true` will always treat input resource as *collection*
341
+ - `false` will always treat input resource as *single object*
342
+
343
+ ### Caching
344
+ Requires a `cache_key` method be defined on model:
345
+
346
+ ```ruby
347
+ class MovieSerializer
348
+ include FastJsonapi::ObjectSerializer
349
+ set_type :movie # optional
350
+ cache_options enabled: true, cache_length: 12.hours
351
+ attributes :name, :year
352
+ end
353
+ ```
354
+
355
+ ### Params
356
+
357
+ In some cases, attribute values might require more information than what is
358
+ available on the record, for example, access privileges or other information
359
+ related to a current authenticated user. The `options[:params]` value covers these
360
+ cases by allowing you to pass in a hash of additional parameters necessary for
361
+ your use case.
362
+
363
+ Leveraging the new params is easy, when you define a custom attribute or relationship with a
364
+ block you opt-in to using params by adding it as a block parameter.
365
+
366
+ ```ruby
367
+ class MovieSerializer
368
+ include FastJsonapi::ObjectSerializer
369
+
370
+ attributes :name, :year
371
+ attribute :can_view_early do |movie, params|
372
+ # in here, params is a hash containing the `:current_user` key
373
+ params[:current_user].is_employee? ? true : false
374
+ end
375
+
376
+ belongs_to :primary_agent do |movie, params|
377
+ # in here, params is a hash containing the `:current_user` key
378
+ params[:current_user].is_employee? ? true : false
379
+ end
380
+ end
381
+
382
+ # ...
383
+ current_user = User.find(cookies[:current_user_id])
384
+ serializer = MovieSerializer.new(movie, {params: {current_user: current_user}})
385
+ serializer.serializable_hash
386
+ ```
387
+
388
+ Custom attributes and relationships that only receive the resource are still possible by defining
389
+ the block to only receive one argument.
390
+
391
+ ### Conditional Attributes
392
+
393
+ 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.
394
+
395
+ ```ruby
396
+ class MovieSerializer
397
+ include FastJsonapi::ObjectSerializer
398
+
399
+ attributes :name, :year
400
+ attribute :release_year, if: Proc.new { |record|
401
+ # Release year will only be serialized if it's greater than 1990
402
+ record.release_year > 1990
403
+ }
404
+
405
+ attribute :director, if: Proc.new { |record, params|
406
+ # The director will be serialized only if the :admin key of params is true
407
+ params && params[:admin] == true
408
+ }
409
+ end
410
+
411
+ # ...
412
+ current_user = User.find(cookies[:current_user_id])
413
+ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
414
+ serializer.serializable_hash
415
+ ```
416
+
417
+ ### Conditional Relationships
418
+
419
+ 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.
420
+
421
+ ```ruby
422
+ class MovieSerializer
423
+ include FastJsonapi::ObjectSerializer
424
+
425
+ # Actors will only be serialized if the record has any associated actors
426
+ has_many :actors, if: Proc.new { |record| record.actors.any? }
427
+
428
+ # Owner will only be serialized if the :admin key of params is true
429
+ belongs_to :owner, if: Proc.new { |record, params| params && params[:admin] == true }
430
+ end
431
+
432
+ # ...
433
+ current_user = User.find(cookies[:current_user_id])
434
+ serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
435
+ serializer.serializable_hash
436
+ ```
437
+
438
+ ### Sparse Fieldsets
439
+
440
+ Attributes and relationships can be selectively returned per record type by using the `fields` option.
441
+
442
+ ```ruby
443
+ class MovieSerializer
444
+ include FastJsonapi::ObjectSerializer
445
+
446
+ attributes :name, :year
447
+ end
448
+
449
+ serializer = MovieSerializer.new(movie, { fields: { movie: [:name] } })
450
+ serializer.serializable_hash
451
+ ```
452
+
453
+ ### Using helper methods
454
+
455
+ You can mix-in code from another ruby module into your serializer class to reuse functions across your app.
456
+
457
+ 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.
458
+
459
+
460
+ ##### Using ActiveSupport::Concern
461
+
462
+ ``` ruby
463
+
464
+ module AvatarHelper
465
+ extend ActiveSupport::Concern
466
+
467
+ class_methods do
468
+ def avatar_url(user)
469
+ user.image.url
470
+ end
471
+ end
472
+ end
473
+
474
+ class UserSerializer
475
+ include FastJsonapi::ObjectSerializer
476
+
477
+ include AvatarHelper # mixes in your helper method as class method
478
+
479
+ set_type :user
480
+
481
+ attributes :name, :email
482
+
483
+ attribute :avatar do |user|
484
+ avatar_url(user)
485
+ end
486
+ end
487
+
488
+ ```
489
+
490
+ ##### Using Plain Old Ruby
491
+
492
+ ``` ruby
493
+ module AvatarHelper
494
+ def avatar_url(user)
495
+ user.image.url
496
+ end
497
+ end
498
+
499
+ class UserSerializer
500
+ include FastJsonapi::ObjectSerializer
501
+
502
+ extend AvatarHelper # mixes in your helper method as class method
503
+
504
+ set_type :user
505
+
506
+ attributes :name, :email
507
+
508
+ attribute :avatar do |user|
509
+ avatar_url(user)
510
+ end
511
+ end
512
+
513
+ ```
514
+
515
+ ### Customizable Options
516
+
517
+ Option | Purpose | Example
518
+ ------------ | ------------- | -------------
519
+ set_type | Type name of Object | ```set_type :movie ```
520
+ key | Key of Object | ```belongs_to :owner, key: :user ```
521
+ set_id | ID of Object | ```set_id :owner_id ``` or ```set_id { |record| "#{record.name.downcase}-#{record.id}" }```
522
+ cache_options | Hash to enable caching and set cache length | ```cache_options enabled: true, cache_length: 12.hours, race_condition_ttl: 10.seconds```
523
+ 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 ```
524
+ object_method_name | Set custom method name to get related objects | ```has_many :locations, object_method_name: :places ```
525
+ record_type | Set custom Object Type for a relationship | ```belongs_to :owner, record_type: :user```
526
+ serializer | Set custom Serializer for a relationship | ```has_many :actors, serializer: :custom_actor``` or ```has_many :actors, serializer: MyApp::Api::V1::ActorSerializer```
527
+ polymorphic | Allows different record types for a polymorphic association | ```has_many :targets, polymorphic: true```
528
+ polymorphic | Sets custom record types for each object class in a polymorphic association | ```has_many :targets, polymorphic: { Person => :person, Group => :group }```
529
+
530
+ ### Instrumentation
531
+
532
+ `fast_jsonapi` also has builtin [Skylight](https://www.skylight.io/) integration. To enable, add the following to an initializer:
533
+
534
+ ```ruby
535
+ require 'fast_jsonapi/instrumentation/skylight'
536
+ ```
537
+
538
+ 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:
539
+
540
+ ```ruby
541
+ require 'fast_jsonapi/instrumentation'
542
+ ```
543
+
544
+ The two instrumented notifcations are supplied by these two constants:
545
+ * `FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION`
546
+ * `FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION`
547
+
548
+ It is also possible to instrument one method without the other by using one of the following require statements:
549
+
550
+ ```ruby
551
+ require 'fast_jsonapi/instrumentation/serializable_hash'
552
+ require 'fast_jsonapi/instrumentation/serialized_json'
553
+ ```
554
+
555
+ Same goes for the Skylight integration:
556
+ ```ruby
557
+ require 'fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash'
558
+ require 'fast_jsonapi/instrumentation/skylight/normalizers/serialized_json'
559
+ ```
560
+
561
+ ## Contributing
562
+ Please see [contribution check](https://github.com/Netflix/fast_jsonapi/blob/master/CONTRIBUTING.md) for more details on contributing
563
+
564
+ ### Running Tests
565
+ We use [RSpec](http://rspec.info/) for testing. We have unit tests, functional tests and performance tests. To run tests use the following command:
566
+
567
+ ```bash
568
+ rspec
569
+ ```
570
+
571
+ To run tests without the performance tests (for quicker test runs):
572
+
573
+ ```bash
574
+ rspec spec --tag ~performance:true
575
+ ```
576
+
577
+ To run tests only performance tests:
578
+
579
+ ```bash
580
+ rspec spec --tag performance:true
581
+ ```