active_model_serializers 0.8.3 → 0.10.0.rc4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (184) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +6 -0
  3. data/.rubocop.yml +86 -0
  4. data/.rubocop_todo.yml +240 -0
  5. data/.simplecov +111 -0
  6. data/.travis.yml +33 -22
  7. data/CHANGELOG.md +358 -6
  8. data/CONTRIBUTING.md +220 -0
  9. data/Gemfile +46 -1
  10. data/{MIT-LICENSE.txt → LICENSE.txt} +3 -2
  11. data/README.md +81 -591
  12. data/Rakefile +68 -11
  13. data/active_model_serializers.gemspec +57 -23
  14. data/appveyor.yml +27 -0
  15. data/docs/ARCHITECTURE.md +120 -0
  16. data/docs/DESIGN.textile +8 -0
  17. data/docs/README.md +35 -0
  18. data/docs/general/adapters.md +162 -0
  19. data/docs/general/caching.md +52 -0
  20. data/docs/general/configuration_options.md +27 -0
  21. data/docs/general/getting_started.md +98 -0
  22. data/docs/general/instrumentation.md +40 -0
  23. data/docs/general/logging.md +14 -0
  24. data/docs/general/rendering.md +153 -0
  25. data/docs/general/serializers.md +207 -0
  26. data/docs/how-open-source-maintained.jpg +0 -0
  27. data/docs/howto/add_pagination_links.md +121 -0
  28. data/docs/howto/add_root_key.md +51 -0
  29. data/docs/howto/outside_controller_use.md +58 -0
  30. data/docs/howto/test.md +152 -0
  31. data/docs/integrations/ember-and-json-api.md +112 -0
  32. data/docs/integrations/grape.md +19 -0
  33. data/docs/jsonapi/schema/schema.json +366 -0
  34. data/docs/jsonapi/schema.md +140 -0
  35. data/lib/action_controller/serialization.rb +41 -37
  36. data/lib/active_model/serializable_resource.rb +72 -0
  37. data/lib/active_model/serializer/adapter/attributes.rb +66 -0
  38. data/lib/active_model/serializer/adapter/base.rb +58 -0
  39. data/lib/active_model/serializer/adapter/cached_serializer.rb +45 -0
  40. data/lib/active_model/serializer/adapter/fragment_cache.rb +111 -0
  41. data/lib/active_model/serializer/adapter/json/fragment_cache.rb +13 -0
  42. data/lib/active_model/serializer/adapter/json.rb +21 -0
  43. data/lib/active_model/serializer/adapter/json_api/deserialization.rb +207 -0
  44. data/lib/active_model/serializer/adapter/json_api/fragment_cache.rb +21 -0
  45. data/lib/active_model/serializer/adapter/json_api/link.rb +44 -0
  46. data/lib/active_model/serializer/adapter/json_api/pagination_links.rb +58 -0
  47. data/lib/active_model/serializer/adapter/json_api.rb +223 -0
  48. data/lib/active_model/serializer/adapter/null.rb +11 -0
  49. data/lib/active_model/serializer/adapter.rb +91 -0
  50. data/lib/active_model/serializer/array_serializer.rb +9 -0
  51. data/lib/active_model/serializer/association.rb +20 -0
  52. data/lib/active_model/serializer/associations.rb +87 -220
  53. data/lib/active_model/serializer/attribute.rb +25 -0
  54. data/lib/active_model/serializer/attributes.rb +82 -0
  55. data/lib/active_model/serializer/belongs_to_reflection.rb +10 -0
  56. data/lib/active_model/serializer/caching.rb +100 -0
  57. data/lib/active_model/serializer/collection_reflection.rb +7 -0
  58. data/lib/active_model/serializer/collection_serializer.rb +47 -0
  59. data/lib/active_model/serializer/configuration.rb +28 -0
  60. data/lib/active_model/serializer/field.rb +56 -0
  61. data/lib/active_model/serializer/fieldset.rb +31 -0
  62. data/lib/active_model/serializer/has_many_reflection.rb +10 -0
  63. data/lib/active_model/serializer/has_one_reflection.rb +10 -0
  64. data/lib/active_model/serializer/include_tree.rb +111 -0
  65. data/lib/active_model/serializer/links.rb +33 -0
  66. data/lib/active_model/serializer/lint.rb +142 -0
  67. data/lib/active_model/serializer/reflection.rb +91 -0
  68. data/lib/active_model/serializer/singular_reflection.rb +7 -0
  69. data/lib/active_model/serializer/type.rb +25 -0
  70. data/lib/active_model/{serializers → serializer}/version.rb +1 -1
  71. data/lib/active_model/serializer.rb +99 -479
  72. data/lib/active_model_serializers/callbacks.rb +55 -0
  73. data/lib/active_model_serializers/deserialization.rb +13 -0
  74. data/lib/active_model_serializers/logging.rb +119 -0
  75. data/lib/active_model_serializers/model.rb +39 -0
  76. data/lib/active_model_serializers/railtie.rb +38 -0
  77. data/lib/active_model_serializers/serialization_context.rb +10 -0
  78. data/lib/active_model_serializers/test/schema.rb +103 -0
  79. data/lib/active_model_serializers/test/serializer.rb +125 -0
  80. data/lib/active_model_serializers/test.rb +7 -0
  81. data/lib/active_model_serializers.rb +20 -92
  82. data/lib/generators/rails/USAGE +6 -0
  83. data/lib/generators/rails/resource_override.rb +10 -0
  84. data/lib/generators/rails/serializer_generator.rb +36 -0
  85. data/lib/generators/rails/templates/serializer.rb.erb +8 -0
  86. data/lib/grape/active_model_serializers.rb +14 -0
  87. data/lib/grape/formatters/active_model_serializers.rb +15 -0
  88. data/lib/grape/helpers/active_model_serializers.rb +16 -0
  89. data/test/action_controller/adapter_selector_test.rb +53 -0
  90. data/test/action_controller/explicit_serializer_test.rb +134 -0
  91. data/test/action_controller/json/include_test.rb +167 -0
  92. data/test/action_controller/json_api/deserialization_test.rb +59 -0
  93. data/test/action_controller/json_api/linked_test.rb +196 -0
  94. data/test/action_controller/json_api/pagination_test.rb +116 -0
  95. data/test/{serialization_scope_name_test.rb → action_controller/serialization_scope_name_test.rb} +11 -15
  96. data/test/action_controller/serialization_test.rb +435 -0
  97. data/test/active_model_serializers/logging_test.rb +77 -0
  98. data/test/active_model_serializers/model_test.rb +9 -0
  99. data/test/active_model_serializers/railtie_test_isolated.rb +57 -0
  100. data/test/active_model_serializers/serialization_context_test.rb +18 -0
  101. data/test/active_model_serializers/test/schema_test.rb +128 -0
  102. data/test/active_model_serializers/test/serializer_test.rb +63 -0
  103. data/test/active_record_test.rb +9 -0
  104. data/test/adapter/fragment_cache_test.rb +38 -0
  105. data/test/adapter/json/belongs_to_test.rb +47 -0
  106. data/test/adapter/json/collection_test.rb +92 -0
  107. data/test/adapter/json/has_many_test.rb +47 -0
  108. data/test/adapter/json_api/belongs_to_test.rb +157 -0
  109. data/test/adapter/json_api/collection_test.rb +97 -0
  110. data/test/adapter/json_api/fields_test.rb +89 -0
  111. data/test/adapter/json_api/has_many_embed_ids_test.rb +45 -0
  112. data/test/adapter/json_api/has_many_explicit_serializer_test.rb +98 -0
  113. data/test/adapter/json_api/has_many_test.rb +145 -0
  114. data/test/adapter/json_api/has_one_test.rb +81 -0
  115. data/test/adapter/json_api/json_api_test.rb +37 -0
  116. data/test/adapter/json_api/linked_test.rb +394 -0
  117. data/test/adapter/json_api/links_test.rb +68 -0
  118. data/test/adapter/json_api/pagination_links_test.rb +115 -0
  119. data/test/adapter/json_api/parse_test.rb +139 -0
  120. data/test/adapter/json_api/resource_type_config_test.rb +71 -0
  121. data/test/adapter/json_api/toplevel_jsonapi_test.rb +84 -0
  122. data/test/adapter/json_test.rb +47 -0
  123. data/test/adapter/null_test.rb +25 -0
  124. data/test/adapter_test.rb +42 -0
  125. data/test/array_serializer_test.rb +36 -73
  126. data/test/collection_serializer_test.rb +100 -0
  127. data/test/fixtures/active_record.rb +56 -0
  128. data/test/fixtures/poro.rb +229 -0
  129. data/test/generators/scaffold_controller_generator_test.rb +24 -0
  130. data/test/generators/serializer_generator_test.rb +57 -0
  131. data/test/grape_test.rb +82 -0
  132. data/test/include_tree/from_include_args_test.rb +26 -0
  133. data/test/include_tree/from_string_test.rb +94 -0
  134. data/test/include_tree/include_args_to_hash_test.rb +64 -0
  135. data/test/lint_test.rb +40 -0
  136. data/test/logger_test.rb +18 -0
  137. data/test/poro_test.rb +9 -0
  138. data/test/serializable_resource_test.rb +27 -0
  139. data/test/serializers/adapter_for_test.rb +166 -0
  140. data/test/serializers/association_macros_test.rb +36 -0
  141. data/test/serializers/associations_test.rb +267 -0
  142. data/test/serializers/attribute_test.rb +123 -0
  143. data/test/serializers/attributes_test.rb +52 -0
  144. data/test/serializers/cache_test.rb +209 -0
  145. data/test/serializers/configuration_test.rb +32 -0
  146. data/test/serializers/fieldset_test.rb +14 -0
  147. data/test/serializers/meta_test.rb +130 -0
  148. data/test/serializers/options_test.rb +21 -0
  149. data/test/serializers/root_test.rb +21 -0
  150. data/test/serializers/serializer_for_test.rb +134 -0
  151. data/test/support/custom_schemas/active_model_serializers/test/schema_test/my/index.json +6 -0
  152. data/test/support/isolated_unit.rb +77 -0
  153. data/test/support/rails5_shims.rb +29 -0
  154. data/test/support/rails_app.rb +25 -0
  155. data/test/support/schemas/active_model_serializers/test/schema_test/my/index.json +6 -0
  156. data/test/support/schemas/active_model_serializers/test/schema_test/my/show.json +6 -0
  157. data/test/support/schemas/custom/show.json +7 -0
  158. data/test/support/schemas/hyper_schema.json +93 -0
  159. data/test/support/schemas/render_using_json_api.json +43 -0
  160. data/test/support/schemas/simple_json_pointers.json +10 -0
  161. data/test/support/serialization_testing.rb +53 -0
  162. data/test/support/simplecov.rb +6 -0
  163. data/test/support/stream_capture.rb +50 -0
  164. data/test/support/test_case.rb +19 -0
  165. data/test/test_helper.rb +55 -24
  166. metadata +358 -42
  167. data/DESIGN.textile +0 -586
  168. data/Gemfile.edge +0 -9
  169. data/bench/perf.rb +0 -43
  170. data/cruft.md +0 -19
  171. data/lib/active_model/array_serializer.rb +0 -104
  172. data/lib/active_record/serializer_override.rb +0 -16
  173. data/lib/generators/resource_override.rb +0 -13
  174. data/lib/generators/serializer/USAGE +0 -9
  175. data/lib/generators/serializer/serializer_generator.rb +0 -42
  176. data/lib/generators/serializer/templates/serializer.rb +0 -19
  177. data/test/association_test.rb +0 -592
  178. data/test/caching_test.rb +0 -96
  179. data/test/generators_test.rb +0 -85
  180. data/test/no_serialization_scope_test.rb +0 -34
  181. data/test/serialization_test.rb +0 -392
  182. data/test/serializer_support_test.rb +0 -51
  183. data/test/serializer_test.rb +0 -1465
  184. data/test/test_fakes.rb +0 -217
@@ -0,0 +1,207 @@
1
+ [Back to Guides](../README.md)
2
+
3
+ # Serializers
4
+
5
+ Given a serializer class:
6
+
7
+ ```ruby
8
+ class SomeSerializer < ActiveModel::Serializer
9
+ end
10
+ ```
11
+
12
+ The following methods may be defined in it:
13
+
14
+ ### Attributes
15
+
16
+ #### ::attributes
17
+
18
+ Serialization of the resource `title` and `body`
19
+
20
+ | In Serializer | #attributes |
21
+ |---------------------------- |-------------|
22
+ | `attributes :title, :body` | `{ title: 'Some Title', body: 'Some Body' }`
23
+ | `attributes :title, :body`<br>`def body "Special #{object.body}" end` | `{ title: 'Some Title', body: 'Special Some Body' }`
24
+
25
+
26
+ #### ::attribute
27
+
28
+ Serialization of the resource `title`
29
+
30
+ | In Serializer | #attributes |
31
+ |---------------------------- |-------------|
32
+ | `attribute :title` | `{ title: 'Some Title' } `
33
+ | `attribute :title, key: :name` | `{ name: 'Some Title' } `
34
+ | `attribute :title { 'A Different Title'}` | `{ title: 'A Different Title' } `
35
+ | `attribute :title`<br>`def title 'A Different Title' end` | `{ title: 'A Different Title' }`
36
+
37
+ [PR please for conditional attributes:)](https://github.com/rails-api/active_model_serializers/pull/1403)
38
+
39
+ ### Associations
40
+
41
+ #### ::has_one
42
+
43
+ e.g.
44
+
45
+ ```ruby
46
+ has_one :bio
47
+ has_one :blog, key: :site
48
+ has_one :maker, virtual_value: { id: 1 }
49
+ ```
50
+
51
+ #### ::has_many
52
+
53
+ e.g.
54
+
55
+ ```ruby
56
+ has_many :comments
57
+ has_many :comments, key: :reviews
58
+ has_many :comments, serializer: CommentPreviewSerializer
59
+ has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]
60
+ has_many :comments, key: :last_comments do
61
+ last(1)
62
+ end
63
+ ```
64
+
65
+ #### ::belongs_to
66
+
67
+ e.g.
68
+
69
+ ```ruby
70
+ belongs_to :author, serializer: AuthorPreviewSerializer
71
+ belongs_to :author, key: :writer
72
+ belongs_to :post
73
+ belongs_to :blog
74
+ def blog
75
+ Blog.new(id: 999, name: 'Custom blog')
76
+ end
77
+ ```
78
+
79
+ ### Caching
80
+
81
+ #### ::cache
82
+
83
+ e.g.
84
+
85
+ ```ruby
86
+ cache key: 'post', expires_in: 0.1, skip_digest: true
87
+ cache expires_in: 1.day, skip_digest: true
88
+ cache key: 'writer', skip_digest: true
89
+ cache only: [:name], skip_digest: true
90
+ cache except: [:content], skip_digest: true
91
+ cache key: 'blog'
92
+ cache only: [:id]
93
+ ```
94
+
95
+ #### #cache_key
96
+
97
+ e.g.
98
+
99
+ ```ruby
100
+ # Uses a custom non-time-based cache key
101
+ def cache_key
102
+ "#{self.class.name.downcase}/#{self.id}"
103
+ end
104
+ ```
105
+
106
+ ### Other
107
+
108
+ #### ::type
109
+
110
+ e.g.
111
+
112
+ ```ruby
113
+ class UserProfileSerializer < ActiveModel::Serializer
114
+ type 'profile'
115
+ end
116
+ ```
117
+
118
+ #### ::link
119
+
120
+ e.g.
121
+
122
+ ```ruby
123
+ link :other, 'https://example.com/resource'
124
+ link :self do
125
+ href "https://example.com/link_author/#{object.id}"
126
+ end
127
+ ```
128
+
129
+ #### #object
130
+
131
+ The object being serialized.
132
+
133
+ #### #root
134
+
135
+ PR please :)
136
+
137
+ #### #scope
138
+
139
+ PR please :)
140
+
141
+ #### #read_attribute_for_serialization(key)
142
+
143
+ The serialized value for a given key. e.g. `read_attribute_for_serialization(:title) #=> 'Hello World'`
144
+
145
+ #### #links
146
+
147
+ PR please :)
148
+
149
+ #### #json_key
150
+
151
+ PR please :)
152
+
153
+ ## Examples
154
+
155
+ Given two models, a `Post(title: string, body: text)` and a
156
+ `Comment(name: string, body: text, post_id: integer)`, you will have two
157
+ serializers:
158
+
159
+ ```ruby
160
+ class PostSerializer < ActiveModel::Serializer
161
+ cache key: 'posts', expires_in: 3.hours
162
+ attributes :title, :body
163
+
164
+ has_many :comments
165
+ end
166
+ ```
167
+
168
+ and
169
+
170
+ ```ruby
171
+ class CommentSerializer < ActiveModel::Serializer
172
+ attributes :name, :body
173
+
174
+ belongs_to :post
175
+ end
176
+ ```
177
+
178
+ Generally speaking, you, as a user of ActiveModelSerializers, will write (or generate) these
179
+ serializer classes.
180
+
181
+ ## More Info
182
+
183
+ For more information, see [the Serializer class on GitHub](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model/serializer.rb)
184
+
185
+ ## Overriding association methods
186
+
187
+ To override an association, call `has_many`, `has_one` or `belongs_to` with a block:
188
+
189
+ ```ruby
190
+ class PostSerializer < ActiveModel::Serializer
191
+ has_many :comments do
192
+ object.comments.active
193
+ end
194
+ end
195
+ ```
196
+
197
+ ## Overriding attribute methods
198
+
199
+ To override an attribute, call `attribute` with a block:
200
+
201
+ ```ruby
202
+ class PostSerializer < ActiveModel::Serializer
203
+ attribute :body do
204
+ object.body.downcase
205
+ end
206
+ end
207
+ ```
Binary file
@@ -0,0 +1,121 @@
1
+ [Back to Guides](../README.md)
2
+
3
+ # How to add pagination links
4
+
5
+ ### JSON API adapter
6
+
7
+ Pagination links will be included in your response automatically as long as
8
+ the resource is paginated and if you are using the ```JsonApi``` adapter.
9
+
10
+ If you want pagination links in your response, use [Kaminari](https://github.com/amatsuda/kaminari)
11
+ or [WillPaginate](https://github.com/mislav/will_paginate).
12
+
13
+ Although the others adapters does not have this feature, it is possible to
14
+ implement pagination links to `JSON` adapter. For more information about it,
15
+ please see in our docs
16
+
17
+ ###### Kaminari examples
18
+
19
+ ```ruby
20
+ #array
21
+ @posts = Kaminari.paginate_array([1, 2, 3]).page(3).per(1)
22
+ render json: @posts
23
+
24
+ #active_record
25
+ @posts = Post.page(3).per(1)
26
+ render json: @posts
27
+ ```
28
+
29
+ ###### WillPaginate examples
30
+
31
+ ```ruby
32
+ #array
33
+ @posts = [1,2,3].paginate(page: 3, per_page: 1)
34
+ render json: @posts
35
+
36
+ #active_record
37
+ @posts = Post.page(3).per_page(1)
38
+ render json: @posts
39
+ ```
40
+
41
+ ```ruby
42
+ ActiveModelSerializers.config.adapter = :json_api
43
+ ```
44
+
45
+ ex:
46
+ ```json
47
+ {
48
+ "data": [
49
+ {
50
+ "type": "articles",
51
+ "id": "3",
52
+ "attributes": {
53
+ "title": "JSON API paints my bikeshed!",
54
+ "body": "The shortest article. Ever.",
55
+ "created": "2015-05-22T14:56:29.000Z",
56
+ "updated": "2015-05-22T14:56:28.000Z"
57
+ }
58
+ }
59
+ ],
60
+ "links": {
61
+ "self": "http://example.com/articles?page[number]=3&page[size]=1",
62
+ "first": "http://example.com/articles?page[number]=1&page[size]=1",
63
+ "prev": "http://example.com/articles?page[number]=2&page[size]=1",
64
+ "next": "http://example.com/articles?page[number]=4&page[size]=1",
65
+ "last": "http://example.com/articles?page[number]=13&page[size]=1"
66
+ }
67
+ }
68
+ ```
69
+
70
+ ActiveModelSerializers pagination relies on a paginated collection with the methods `current_page`, `total_pages`, and `size`, such as are supported by both [Kaminari](https://github.com/amatsuda/kaminari) or [WillPaginate](https://github.com/mislav/will_paginate).
71
+
72
+
73
+ ### JSON adapter
74
+
75
+ If you are using `JSON` adapter, pagination links will not be included automatically, but it is possible to do so using `meta` key.
76
+
77
+ In your action specify a custom serializer.
78
+ ```ruby
79
+ render json: @posts, serializer: PaginatedSerializer, each_serializer: PostPreviewSerializer
80
+ ```
81
+
82
+ And then, you could do something like the following class.
83
+ ```ruby
84
+ class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer
85
+ def initialize(object, options={})
86
+ meta_key = options[:meta_key] || :meta
87
+ options[meta_key] ||= {}
88
+ options[meta_key] = {
89
+ current_page: object.current_page,
90
+ next_page: object.next_page,
91
+ prev_page: object.prev_page,
92
+ total_pages: object.total_pages,
93
+ total_count: object.total_count
94
+ }
95
+ super(object, options)
96
+ end
97
+ end
98
+ ```
99
+ ex.
100
+ ```json
101
+ {
102
+ "articles": [
103
+ {
104
+ "id": 2,
105
+ "title": "JSON API paints my bikeshed!",
106
+ "body": "The shortest article. Ever."
107
+ }
108
+ ],
109
+ "meta": {
110
+ "current_page": 3,
111
+ "next_page": 4,
112
+ "prev_page": 2,
113
+ "total_pages": 10,
114
+ "total_count": 10
115
+ }
116
+ }
117
+ ```
118
+
119
+ ### Attributes adapter
120
+
121
+ This adapter does not allow us to use `meta` key, due to that it is not possible to add pagination links.
@@ -0,0 +1,51 @@
1
+ # How to add root key
2
+
3
+ Add the root key to your API is quite simple with ActiveModelSerializers. The **Adapter** is what determines the format of your JSON response. The default adapter is the ```Attributes``` which doesn't have the root key, so your response is something similar to:
4
+
5
+ ```json
6
+ {
7
+ "id": 1,
8
+ "title": "Awesome Post Tile",
9
+ "content": "Post content"
10
+ }
11
+ ```
12
+
13
+ In order to add the root key you need to use the ```JSON``` Adapter, you can change this in an initializer:
14
+
15
+ ```ruby
16
+ ActiveModelSerializers.config.adapter = :json
17
+ ```
18
+
19
+ You can also specify a class as adapter, as long as it complies with the ActiveModelSerializers adapters interface.
20
+ It will add the root key to all your serialized endpoints.
21
+
22
+ ex:
23
+
24
+ ```json
25
+ {
26
+ "post": {
27
+ "id": 1,
28
+ "title": "Awesome Post Tile",
29
+ "content": "Post content"
30
+ }
31
+ }
32
+ ```
33
+
34
+ or if it returns a collection:
35
+
36
+ ```json
37
+ {
38
+ "posts": [
39
+ {
40
+ "id": 1,
41
+ "title": "Awesome Post Tile",
42
+ "content": "Post content"
43
+ },
44
+ {
45
+ "id": 2,
46
+ "title": "Another Post Tile",
47
+ "content": "Another post content"
48
+ }
49
+ ]
50
+ }
51
+ ```
@@ -0,0 +1,58 @@
1
+ [Back to Guides](../README.md)
2
+
3
+ ## Using ActiveModelSerializers Outside Of A Controller
4
+
5
+ ### Serializing a resource
6
+
7
+ In ActiveModelSerializers versions 0.10 or later, serializing resources outside of the controller context is fairly simple:
8
+
9
+ ```ruby
10
+ # Create our resource
11
+ post = Post.create(title: "Sample post", body: "I love Active Model Serializers!")
12
+
13
+ # Optional options parameters
14
+ options = {}
15
+
16
+ # Create a serializable resource instance
17
+ serializable_resource = ActiveModel::SerializableResource.new(post, options)
18
+
19
+ # Convert your resource into json
20
+ model_json = serializable_resource.as_json
21
+ ```
22
+
23
+ ### Looking up the Serializer for a Resource
24
+
25
+ If you want to retrieve a serializer for a specific resource, you can do the following:
26
+
27
+ ```ruby
28
+ # Create our resource
29
+ post = Post.create(title: "Another Example", body: "So much fun.")
30
+
31
+ # Optional options parameters
32
+ options = {}
33
+
34
+ # Retrieve the default serializer for posts
35
+ serializer = ActiveModel::Serializer.serializer_for(post, options)
36
+ ```
37
+
38
+ You could also retrieve the serializer via:
39
+
40
+ ```ruby
41
+ ActiveModel::SerializableResource.new(post, options).serializer
42
+ ```
43
+
44
+ Both approaches will return an instance, if any, of the resource's serializer.
45
+
46
+ ## Serializing before controller render
47
+
48
+ At times, you might want to use a serializer without rendering it to the view. For those cases, you can create an instance of `ActiveModel::SerializableResource` with
49
+ the resource you want to be serialized and call `.as_json`.
50
+
51
+ ```ruby
52
+ def create
53
+ message = current_user.messages.create!(message_params)
54
+ message_json = ActiveModel::SerializableResource.new(message).as_json
55
+ MessageCreationWorker.perform(message_json)
56
+ head 204
57
+ end
58
+ ```
@@ -0,0 +1,152 @@
1
+ # How to test
2
+
3
+ ## Controller Serializer Usage
4
+
5
+ ActiveModelSerializers provides a `assert_serializer` method to be used on your controller tests to
6
+ assert that a specific serializer was used.
7
+
8
+ ```ruby
9
+ class PostsControllerTest < ActionController::TestCase
10
+ test "should render post serializer" do
11
+ get :index
12
+ assert_serializer "PostSerializer"
13
+ end
14
+ end
15
+ ```
16
+
17
+ See [ActiveModelSerializers::Test::Serializer](../../lib/active_model_serializers/test/serializer.rb)
18
+ for more examples and documentation.
19
+
20
+ ## Serialization against a schema
21
+
22
+ ### Dependencies
23
+
24
+ To use the `assert_response_schema` you need to have the
25
+ [`json_schema`](https://github.com/brandur/json_schema) on your Gemfile. Please
26
+ add it to your Gemfile and run `$ bundle install`.
27
+
28
+ ### Minitest test helpers
29
+
30
+ ActiveModelSerializers provides a `assert_response_schema` method to be used on your controller tests to
31
+ assert the response against a [JSON Schema](http://json-schema.org/). Let's take
32
+ a look in an example.
33
+
34
+ ```ruby
35
+ class PostsController < ApplicationController
36
+ def show
37
+ @post = Post.find(params[:id])
38
+
39
+ render json: @post
40
+ end
41
+ end
42
+ ```
43
+
44
+ To test the `posts#show` response of this controller we need to create a file
45
+ named `test/support/schemas/posts/show.json`. The helper uses a naming convention
46
+ to locate the file.
47
+
48
+ This file is a JSON Schema representation of our response.
49
+
50
+ ```json
51
+ {
52
+ "properties": {
53
+ "title" : { "type" : "string" },
54
+ "content" : { "type" : "string" }
55
+ }
56
+ }
57
+ ```
58
+
59
+ With all in place we can go to our test and use the helper.
60
+
61
+ ```ruby
62
+ class PostsControllerTest < ActionController::TestCase
63
+ test "should render right response" do
64
+ get :index
65
+ assert_response_schema
66
+ end
67
+ end
68
+ ```
69
+
70
+ #### Load a custom schema
71
+
72
+ If we need to use another schema, for example when we have a namespaced API that
73
+ shows the same response, we can pass the path of the schema.
74
+
75
+ ```ruby
76
+ module V1
77
+ class PostsController < ApplicationController
78
+ def show
79
+ @post = Post.find(params[:id])
80
+
81
+ render json: @post
82
+ end
83
+ end
84
+ end
85
+ ```
86
+
87
+ ```ruby
88
+ class V1::PostsControllerTest < ActionController::TestCase
89
+ test "should render right response" do
90
+ get :index
91
+ assert_response_schema('posts/show.json')
92
+ end
93
+ end
94
+ ```
95
+
96
+ #### Change the schema path
97
+
98
+ By default all schemas are created at `test/support/schemas`. If we are using
99
+ RSpec for example we can change this to `spec/support/schemas` defining the
100
+ default schema path in an initializer.
101
+
102
+ ```ruby
103
+ ActiveModelSerializers.config.schema_path = 'spec/support/schemas'
104
+ ```
105
+
106
+ #### Using with the Heroku’s JSON Schema-based tools
107
+
108
+ To use the test helper with the [prmd](https://github.com/interagent/prmd) and
109
+ [committee](https://github.com/interagent/committee).
110
+
111
+ We need to change the schema path to the recommended by prmd:
112
+
113
+ ```ruby
114
+ ActiveModelSerializers.config.schema_path = 'docs/schema/schemata'
115
+ ```
116
+
117
+ We also need to structure our schemata according to Heroku's conventions
118
+ (e.g. including
119
+ [required metadata](https://github.com/interagent/prmd/blob/master/docs/schemata.md#meta-data)
120
+ and [links](https://github.com/interagent/prmd/blob/master/docs/schemata.md#links).
121
+
122
+ #### JSON Pointers
123
+
124
+ If we plan to use [JSON
125
+ Pointers](http://spacetelescope.github.io/understanding-json-schema/UnderstandingJSONSchema.pdf) we need to define the `id` attribute on the schema. Example:
126
+
127
+ ```js
128
+ // attributes.json
129
+
130
+ {
131
+ "id": "file://attributes.json#",
132
+ "properties": {
133
+ "name" : { "type" : "string" },
134
+ "description" : { "type" : "string" }
135
+ }
136
+ }
137
+ ```
138
+
139
+ ```js
140
+ // show.json
141
+
142
+ {
143
+ "properties": {
144
+ "name": {
145
+ "$ref": "file://attributes.json#/properties/name"
146
+ },
147
+ "description": {
148
+ "$ref": "file://attributes.json#/properties/description"
149
+ }
150
+ }
151
+ }
152
+ ```
@@ -0,0 +1,112 @@
1
+ [Back to Guides](../README.md)
2
+
3
+ # Integrating with Ember and JSON API
4
+
5
+ - [Preparation](./ember-and-json-api.md#preparation)
6
+ - [Server-Side Changes](./ember-and-json-api.md#server-side-changes)
7
+ - [Adapter Changes](./ember-and-json-api.md#adapter-changes)
8
+ - [Serializer Changes](./ember-and-json-api.md#serializer-changes)
9
+ - [Including Nested Resources](./ember-and-json-api.md#including-nested-resources)
10
+
11
+ ## Preparation
12
+
13
+ Note: This guide assumes that `ember-cli` is used for your ember app.
14
+
15
+ The JSON API specification calls for hyphens for multi-word separators. ActiveModelSerializers uses underscores.
16
+ To solve this, in Ember, both the adapter and the serializer will need some modifications:
17
+
18
+ ### Server-Side Changes
19
+
20
+ there are multiple mimetypes for json that should all be parsed similarly, so
21
+ in `config/initializers/mime_types.rb`:
22
+ ```ruby
23
+ api_mime_types = %W(
24
+ application/vnd.api+json
25
+ text/x-json
26
+ application/json
27
+ )
28
+
29
+ Mime::Type.unregister :json
30
+ Mime::Type.register 'application/json', :json, api_mime_types
31
+ ```
32
+
33
+ ### Adapter Changes
34
+
35
+ ```javascript
36
+ // app/adapters/application.js
37
+ import DS from 'ember-data';
38
+ import ENV from "../config/environment";
39
+
40
+ export default DS.JSONAPIAdapter.extend({
41
+ namespace: 'api',
42
+ // if your rails app is on a different port from your ember app
43
+ // this can be helpful for development.
44
+ // in production, the host for both rails and ember should be the same.
45
+ host: ENV.host,
46
+
47
+ // allows the multiword paths in urls to be underscored
48
+ pathForType: function(type) {
49
+ let underscored = Ember.String.underscore(type);
50
+ return Ember.String.pluralize(underscored);
51
+ },
52
+
53
+ // allows queries to be sent along with a findRecord
54
+ // hopefully Ember / EmberData will soon have this built in
55
+ // ember-data issue tracked here:
56
+ // https://github.com/emberjs/data/issues/3596
57
+ urlForFindRecord(id, modelName, snapshot) {
58
+ let url = this._super(...arguments);
59
+ let query = Ember.get(snapshot, 'adapterOptions.query');
60
+ if(query) {
61
+ url += '?' + Ember.$.param(query);
62
+ }
63
+ return url;
64
+ }
65
+ });
66
+ ```
67
+
68
+ ### Serializer Changes
69
+
70
+ ```javascript
71
+ // app/serializers/application.js
72
+ import Ember from 'ember';
73
+ import DS from 'ember-data';
74
+ var underscore = Ember.String.underscore;
75
+
76
+ export default DS.JSONAPISerializer.extend({
77
+ keyForAttribute: function(attr) {
78
+ return underscore(attr);
79
+ },
80
+
81
+ keyForRelationship: function(rawKey) {
82
+ return underscore(rawKey);
83
+ }
84
+ });
85
+
86
+ ```
87
+
88
+ ## Including Nested Resources
89
+
90
+ Previously, `store.find` and `store.findRecord` did not allow specification of any query params.
91
+ The ActiveModelSerializers default for the `include` parameter is to be `nil` meaning that if any associations are defined in your serializer, only the `id` and `type` will be in the `relationships` structure of the JSON API response.
92
+ For more on `include` usage, see: [The JSON API include examples](./../general/adapters.md#JSON-API)
93
+
94
+ With the above modifications, you can execute code as below in order to include nested resources while doing a find query.
95
+
96
+ ```javascript
97
+ store.findRecord('post', postId, { adapterOptions: { query: { include: 'comments' } } });
98
+ ```
99
+ will generate the path `/posts/{postId}?include='comments'`
100
+
101
+ So then in your controller, you'll want to be sure to have something like:
102
+ ```ruby
103
+ render json: @post, include: params[:include]
104
+ ```
105
+
106
+ If you want to use `include` on a collection, you'd write something like this:
107
+
108
+ ```javascript
109
+ store.query('post', { include: 'comments' });
110
+ ```
111
+
112
+ which will generate the path `/posts?include='comments'`