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