rails-surrender 7.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +123 -0
  3. data/LICENSE +674 -0
  4. data/README.md +326 -0
  5. data/lib/rails/surrender/config/locales/en.yml +3 -0
  6. data/lib/rails/surrender/controller_additions.rb +27 -72
  7. data/lib/rails/surrender/fields/asks.rb +50 -0
  8. data/lib/rails/surrender/fields/attribute.rb +34 -0
  9. data/lib/rails/surrender/fields/expand.rb +65 -0
  10. data/lib/rails/surrender/fields/field_tree.rb +71 -0
  11. data/lib/rails/surrender/fields/id_list.rb +38 -0
  12. data/lib/rails/surrender/fields/node.rb +86 -0
  13. data/lib/rails/surrender/menu/endpoint_menu.rb +21 -0
  14. data/lib/rails/surrender/menu/field.rb +20 -0
  15. data/lib/rails/surrender/menu/field_menu.rb +58 -0
  16. data/lib/rails/surrender/menu/filter.rb +16 -0
  17. data/lib/rails/surrender/menu/menu.rb +27 -0
  18. data/lib/rails/surrender/menu/menu_param.rb +28 -0
  19. data/lib/rails/surrender/menu/selection_menu.rb +33 -0
  20. data/lib/rails/surrender/model_additions.rb +47 -32
  21. data/lib/rails/surrender/params/list_param.rb +23 -0
  22. data/lib/rails/surrender/railtie.rb +31 -9
  23. data/lib/rails/surrender/render/resource.rb +11 -30
  24. data/lib/rails/surrender/selection/filtering.rb +144 -0
  25. data/lib/rails/surrender/selection/page_size.rb +37 -0
  26. data/lib/rails/surrender/selection/selected.rb +50 -0
  27. data/lib/rails/surrender/selection/selection.rb +70 -0
  28. data/lib/rails/surrender/selection/sorting.rb +61 -0
  29. data/lib/rails/surrender/version.rb +1 -1
  30. data/lib/rails/surrender.rb +21 -12
  31. metadata +69 -41
  32. data/lib/rails/surrender/config/initializers/active_record_associations_patch.rb +0 -17
  33. data/lib/rails/surrender/config/initializers/active_record_preloader_patch.rb +0 -20
  34. data/lib/rails/surrender/helpers/filter_builder.rb +0 -50
  35. data/lib/rails/surrender/helpers/pagination_builder.rb +0 -25
  36. data/lib/rails/surrender/helpers/query_param_parser.rb +0 -98
  37. data/lib/rails/surrender/helpers/sort_builder.rb +0 -56
  38. data/lib/rails/surrender/model_filter_scopes.rb +0 -56
  39. data/lib/rails/surrender/render/configuration/inclusion_mapper_logic.rb +0 -69
  40. data/lib/rails/surrender/render/configuration/instance_logic.rb +0 -88
  41. data/lib/rails/surrender/render/configuration.rb +0 -93
  42. data/lib/rails/surrender/render/count.rb +0 -21
  43. data/lib/rails/surrender/render/ids.rb +0 -21
  44. data/lib/rails/surrender/render/resource/collection.rb +0 -26
  45. data/lib/rails/surrender/render/resource/inclusion_mapper.rb +0 -48
  46. data/lib/rails/surrender/render/resource/instance.rb +0 -75
  47. data/test/surrender_test.rb +0 -9
  48. data/test/test_helper.rb +0 -21
data/README.md ADDED
@@ -0,0 +1,326 @@
1
+ # Surrender
2
+ A JSON rendering platform for Rails APIs. Provides many controls through URL query parameters for clients to craft
3
+ API responses from your resources.
4
+
5
+ ## Requirements
6
+ * Ruby 3.3 or newer
7
+ * Rails 7.0 through 8.1
8
+
9
+ CI runs the full suite on these Ruby and Rails versions:
10
+
11
+ | Ruby | Rails 7.0 | Rails 7.1 | Rails 7.2 | Rails 8.0 | Rails 8.1 |
12
+ |------|:---------:|:---------:|:---------:|:---------:|:---------:|
13
+ | 3.3 | ✅ | ✅ | ✅ | ✅ | ✅ |
14
+ | 3.4 | | | | ✅ | ✅ |
15
+ | 4.0 | | | | ✅ | ✅ |
16
+
17
+ 8.x is the current version and supports Rails 7.0 through 8.1. Its major version changes only with breaking
18
+ changes. Every other change, including new features, goes in the patch digit, unless a release changes which Rails
19
+ minor versions it supports. 7.0.0, on the `7-0-stable` branch, is the earlier version for Rails 7.0, and gets no new
20
+ features.
21
+
22
+ Rails 8.0 and earlier are not compatible with version 3 of the `json` gem, so apps on them should keep `json` below 3:
23
+
24
+ ```ruby
25
+ gem 'json', '< 3'
26
+ ```
27
+
28
+ ## Features
29
+ Surrender adds a number of helpful features to API requests, through URL query parameters to craft the structure of the
30
+ response:
31
+
32
+ ### Sorting
33
+ Most attributes on the requested resource can be targeted for sorting. Sorting is provided for to the API with the
34
+ 'sort' query parameter.
35
+
36
+ | example query param | description |
37
+ |---------------------|-----------------------------------------------------------|
38
+ | `sort=name` | Sort the results by the `name` attribute |
39
+ | `sort=-created_at` | Sort the results in reverse by the `created_at` attribute |
40
+ | `sort=author.name` | Sort the results by the `name` of each result's `author` |
41
+
42
+ Sorting by a column of an association works for associations that hold one record, such as `belongs_to` and `has_one`.
43
+ An association that holds many would repeat each result once per associated record, so it is rejected.
44
+
45
+ A model can define its own sorts as scopes named `sort_by_<name>`, which take the direction, `'ASC'` or `'DESC'`. A
46
+ sort the model defines wins over a column of the same name, so `sort_by_title` can sort titles without regard to case:
47
+
48
+ ```ruby
49
+ scope :sort_by_title, ->(direction) { order(Arel.sql("LOWER(title) #{direction}")) }
50
+ ```
51
+
52
+
53
+ ### Pagination
54
+ Pagination is provided internally using the 'kaminari' gem. Access is provided to the API with the `page` and `per`
55
+ query parameters
56
+
57
+ | example query param | description |
58
+ |---------------------|------------------------------------|
59
+ | `per=20` | Request 20 results per page |
60
+ | `page=2` | Request the second page of results |
61
+
62
+ A page holds 50 resources unless the request sets `per`, and never more than 100, whatever `per` asks for. Both numbers
63
+ can be changed in the app's configuration (see Setup). `page` and `per` take positive whole numbers; anything else is
64
+ rejected with a `Rails::Surrender::Error`.
65
+
66
+ Paginated results will populate an `X-Pagination` header in the result set that provides a hash of the paginated
67
+ details. The hash is structured like:
68
+
69
+ ```json
70
+ {
71
+ "total": 70,
72
+ "page_total": 3,
73
+ "page": 2,
74
+ "previous_page": 1,
75
+ "next_page": 3,
76
+ "last_page": 3,
77
+ "per_page": 25,
78
+ "offset": 25
79
+ }
80
+ ```
81
+
82
+ ### Filtering
83
+ `rails-surrender` adds a number of scopes to your models for filtering, and provides access to the filters with the
84
+ `filter` query parameter. Most columns are provided with an equality filter and can be filtered on matching values.
85
+ Date and Time columns are also provided with `_before` and `_after` filters, named after the column without its `_at`
86
+ suffix, which select records strictly before or after the given date or time. Examples are provided below:
87
+
88
+ Note: Time-based filters take an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date or time, such as
89
+ `'2022-01-01'`, `'2022-01-01T13:30:00Z'` or `'2022-01-01T13:30:00-05:00'`, surrounded by single or double quotes. A time
90
+ without an offset is in the app's time zone. Any other value is rejected with a `Rails::Surrender::Error`.
91
+
92
+ | example query param | description |
93
+ |-----------------------------------------------|-----------------------------------------------------------------------------------|
94
+ | `filter=active:false` | filter for resources with the `active` attribute set to false |
95
+ | `filter=state:TX` | filter for resources with the `state` attribute of `TX` |
96
+ | `filter=created_before:'2022-01-01'` | filter for resources with a `created_at` value _before_ Jan 01, 2022 |
97
+ | `filter=created_after:'2022-01-01'` | filter for resources with a `created_at` value _after_ Jan 01, 2022 |
98
+ | `filter=created_after:'2022-01-01T13:30:00Z'` | filter for resources with a `created_at` value _after_ 1:30pm UTC on Jan 01, 2022 |
99
+
100
+
101
+ ### Counting
102
+ Instead of rendering a full list of resources, `rails-surrender` can return only the _count_ of the number of resources
103
+ that _would_ be returned. A count ignores pagination: it counts every resource the filters select, not just one page. This can be useful when combined with filters for basic reporting. Access is provided with
104
+ the `count` query parameter.
105
+
106
+ | example query param | description |
107
+ |-----------------------------------------------------------------|------------------------------------------------------|
108
+ | `count` | count the number of resources |
109
+ | `filter=state:TX&count` | count the number of resources in the `state` of 'TX' |
110
+ | `filter=state:TX&count` | count the number of resources in the `state` of 'TX' |
111
+ | `filter=created_before:'2022-01-01'&count` | count the number of resources created before 2022 |
112
+
113
+
114
+ ### Including
115
+ the `include` (and `exclude` described below) directive provides an easy but powerful mechanism for crafting the shape
116
+ of the response. For models that provide additional attributes or associations that are not rendered by default (see
117
+ setup below) the `include` query parameter can be used to request those attributes and associations be rendered in the
118
+ request. The `include` parameter can request multiple attributes and associations, and for associations can include
119
+ additional values on nested resources. Examples below:
120
+
121
+ | example query param | description |
122
+ |---------------------------------------------------------------------------|-------------------------------------------------------------------------|
123
+ | `include=created_at, updated_at` | include the `created_at` and `updated at` attributes of the resource(s) |
124
+ | `include=work_orders` | include the `work_orders` association of the resource(s) |
125
+ | `include=work_orders:[activities]` | include the `work_orders` and it's `activities` association |
126
+ | `include=created_at, work_orders:[created_at, activities:[created_at ]]` | combine various attributes and associations and nested results |
127
+
128
+ Each resource renders its `id` first, then its other attributes, then its `*_ids` lists, then its associations. Within
129
+ each group, the model's default fields come first, then those the controller includes, then those the request includes.
130
+
131
+
132
+ ### Excluding
133
+ Exclude (and exclude below) provide an easy but powerful mechanism for crafting the shape of the response. Excluding
134
+ works like the reverse of include. Models may define attributes or associations that are rendered by default, but
135
+ exclude can be used to prevent rendering of those attributes. Examples below:
136
+
137
+ | example query param | description |
138
+ |----------------------------------|------------------------------------------------------------------------------------------------------|
139
+ | `exclude=created_at, updated_at` | exclude the `created_at` and `updated at` attributes of the resource(s) that are rendered by default |
140
+ | `exclude=work_orders` | include the `work_orders` association of the resource(s) that is rendered by default |
141
+ | `exclude=activities:[creator]` | keep the default `activities` association, but leave out each activity's `creator` |
142
+
143
+ To list only the ids of the resources, exclude every other field they render by default, such as
144
+ `exclude=title,genre,author`.
145
+
146
+
147
+ ### Menus
148
+ An endpoint can describe what it accepts. With menus turned on (see [Configuration](#configuration)), the `menu` query
149
+ parameter renders the endpoint's _menu_ instead of its resources: the fields it renders by default and those a request
150
+ may include, nested by expand, and, for a collection, the filters, sorts and page size a request may use.
151
+
152
+ ```
153
+ GET /books?menu
154
+ ```
155
+
156
+ ```json
157
+ {
158
+ "fields": [
159
+ { "name": "id", "type": "integer", "default": true },
160
+ { "name": "title", "type": "string", "default": true },
161
+ { "name": "pages", "type": "integer", "default": false },
162
+ { "name": "chapter_ids", "type": "array", "default": false },
163
+ { "name": "author", "type": "object", "default": false,
164
+ "fields": [
165
+ { "name": "id", "type": "integer", "default": true },
166
+ { "name": "name", "type": "string", "default": true }
167
+ ] },
168
+ { "name": "chapters", "type": "array", "default": false,
169
+ "fields": [ ... ] }
170
+ ],
171
+ "selection": {
172
+ "filters": {
173
+ "title": { "type": "string" },
174
+ "published_before": { "type": "datetime" },
175
+ "long": { "type": null }
176
+ },
177
+ "sorts": ["id", "title", "author.name", "title_length"],
178
+ "page": { "default": 50, "max": 100 }
179
+ }
180
+ }
181
+ ```
182
+
183
+ - `fields` are listed in the order they render. Only an expand has `fields` of its own, and expands that would loop
184
+ back into a model above are left out, as they never render.
185
+ - Each field's `type` is what it renders as. An attribute's is the Rails type of its column, such as `string` or
186
+ `datetime`, or `null` for a method the model defines. An `_ids` list is an `array`, and an expand is an `object`, or
187
+ an `array` of objects for a collection association.
188
+ - The controller's own `include:` and `exclude:` are applied, so a field the controller includes is listed as a
189
+ default. A field the controller excludes is listed as available if a request may still include it.
190
+ - Each filter's `type` is the Rails type of the column it compares, such as `datetime` for the `_before` and `_after`
191
+ filters, which take ISO 8601 times. A filter the model defines itself has a `null` type.
192
+ - `selection` is `null` for an endpoint that renders a single record, and `page` is `null` when the controller skips
193
+ pagination. An endpoint that surrenders a hash, an array or `nil` has `null` for both parts, as no ask applies to it.
194
+ - A menu lists names and types only. The syntax of each ask is described in the sections above.
195
+
196
+ A menu ignores every other ask in the request, and loads no records. The controller still runs its action, its
197
+ callbacks and anything before `surrender`, so a member route needs an id that exists, and the menu is only as visible
198
+ as the endpoint itself. A block passed to `surrender` doesn't decorate a menu, so every endpoint's menu has the same
199
+ shape.
200
+
201
+ Abilities aren't applied to a menu. They decide which records render inside a field, not which fields a model offers,
202
+ so a menu may list an expand whose records the current user can't read.
203
+
204
+ An STI subclass renders its own fields. The menu of a collection lists its base model's fields, so records of a
205
+ subclass may render more default fields than it lists. A request may only include fields the base model offers.
206
+
207
+ ## Example Project
208
+ A full working example project is provided in the [rails-surrender-demo](https://github.com/smmcbride/rails-surrender-demo)
209
+ repository. It provides several models and endpoints demonstrating a working configuration of `rails-surrender`. The
210
+ project provides seed data, a browser explorer where each query parameter is a checkbox and the response is shown as
211
+ you send it, and a `bin/http` command for trying each query parameter from the terminal.
212
+
213
+
214
+ ## Installation
215
+
216
+ This project is intended to be used in a Ruby on Rails project. To install, simply add this your Gemfile:
217
+
218
+ ```ruby
219
+ gem 'rails-surrender', '~> 8.0'
220
+ ```
221
+
222
+ and bundle:
223
+
224
+ ```sh
225
+ % bundle
226
+ ```
227
+
228
+ ## Setup
229
+ Surrender setup begins in your models. To enable rendering of a model with this gem, call `surrenders` on it with the
230
+ fields to render by default, and optionally `available:` with the fields API clients can add with the `include` query
231
+ parameter. A field can be any model attribute or method, a `*_ids` attribute such as `chapter_ids`, or an association
232
+ such as one defined with `has_many` or `belongs_to`. Surrender renders associations as nested resources, using the
233
+ associated model's own `surrenders` fields, and renders every other field as an attribute.
234
+
235
+ An example invocation of the `surrenders` method is provided below:
236
+ ```ruby
237
+ surrenders :id, :title, :description, :status, :activities,
238
+ available: [:created_at, :updated_at, :user]
239
+ ```
240
+
241
+ A model that doesn't call `surrenders` renders its `id` and `created_at`. A subclass that calls `surrenders` adds its
242
+ fields to those of its superclass, and its records render them wherever they appear, including in a collection of the
243
+ superclass.
244
+
245
+ Surrender can't expand a polymorphic `belongs_to`, because it works out the fields to render before any record loads,
246
+ when the association has no class yet. Listing one as a field raises `ArgumentError`.
247
+
248
+ To invoke surrender in your controllers, simply end your controller action with a call to `surrender` with the
249
+ resource you wish to render. An example controller action is provided below:
250
+
251
+ ```ruby
252
+ def index
253
+ books = Book.all
254
+ surrender books
255
+ end
256
+ ```
257
+
258
+
259
+ ### Configuration
260
+
261
+ Surrender's page sizes are set in `config/application.rb`, or per environment in `config/environments/*.rb`:
262
+
263
+ ```ruby
264
+ config.surrender.default_per_page = 50 # the page size when a request doesn't set `per`
265
+ config.surrender.max_per_page = 100 # the most a page holds, whatever `per` asks for; nil removes the limit
266
+ ```
267
+
268
+ Menus are off unless the app turns them on, as they show the app's column names and the names of its own filters and
269
+ sorts. Set them per environment to keep them out of production:
270
+
271
+ ```ruby
272
+ config.surrender.menus = true # answer the menu query parameter; false by default
273
+ config.surrender.menu_param = 'menu' # the name it's asked with, such as 'docs'
274
+ ```
275
+
276
+ While menus are off, `menu` is an ordinary query parameter, so an app's own parameter of that name works as usual. The
277
+ app won't boot if `menu_param` is blank or is the name of a parameter surrender already reads, such as `count`.
278
+
279
+ The app won't boot if the default is larger than the limit, or either isn't a positive whole number. Kaminari's own
280
+ page size settings don't apply to surrender's pages.
281
+
282
+ ### Describing what a request may ask
283
+
284
+ `surrender_menu` lists everything a request may ask of a model, read from the same rules that check requests. Unlike
285
+ an endpoint's [menu](#menus), it doesn't know a controller's `include:` and `exclude:`:
286
+
287
+ ```ruby
288
+ menu = Book.surrender_menu
289
+ menu.fields # each with its name, type (such as :string, :array or :object), default?, and an expand's field menu
290
+ menu.selection.filters # each with its name and the column it compares, or nil for a filter the model defines
291
+ menu.selection.sorts # ['id', 'title', ..., 'author.name', 'title_length']
292
+ menu.selection.page_size.default, menu.selection.page_size.max # 50 and 100 unless configured
293
+ ```
294
+
295
+ The fields make up the model's field menu, which applies wherever the model renders, including inside an expand. The
296
+ filters, sorts and page size make up its selection menu, which applies only to the records at the top of a response.
297
+ `menu.filters`, `menu.sorts` and `menu.page_size` answer from the selection menu too.
298
+
299
+ ### Additional Notes
300
+
301
+ Surrender prevents circular renderings. If a `Book` model, for example, expands its `Author`, and `Author` expands its
302
+ `books`, then surrender leaves out the `books` of an author rendered inside a book. It never expands an association
303
+ into a model already rendered above it, and it treats an STI subclass as its base class when checking.
304
+
305
+ Surrender prevents un-authorized access to associated resources by invoking the `current_ability` rule-set from the
306
+ CanCanCan gem, if it is used in your Rails project. Any controller method named `current_ability`, public or private,
307
+ that returns an object responding to `can?(:read, record)` is used the same way. If neither is present it will allow
308
+ full access to associated resources. A nested record the ability can't read renders as `null`, as a missing one does,
309
+ and is left out of a nested collection.
310
+
311
+ ## Development
312
+
313
+ The test suite boots a small Rails app (`spec/dummy`) against an in-memory SQLite database. Run it against the
314
+ latest Rails with:
315
+
316
+ ```sh
317
+ bundle install
318
+ bundle exec rake
319
+ ```
320
+
321
+ `rake` runs both the specs and RuboCop. To run the specs against each supported Rails version:
322
+
323
+ ```sh
324
+ bundle exec appraisal install
325
+ bundle exec appraisal rspec
326
+ ```
@@ -6,7 +6,10 @@ en:
6
6
  incorrect_format: "The %{param} parameter was improperly formatted."
7
7
  filter:
8
8
  not_available: "%{param} is not a valid filter parameter."
9
+ invalid_time: "%{param} needs an ISO 8601 date or time, such as '2026-01-01' or '2026-01-01T13:30:00Z', not '%{value}'."
9
10
  include:
10
11
  not_available: "%{param} is not a valid include parameter."
12
+ pagination:
13
+ invalid: "%{param} needs a positive whole number, not '%{value}'."
11
14
  sort:
12
15
  invalid_column: "%{param} is not a valid sort parameter."
@@ -1,10 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'helpers/query_param_parser'
4
- require_relative 'helpers/filter_builder'
5
- require_relative 'helpers/pagination_builder'
6
- require_relative 'helpers/sort_builder'
7
-
8
3
  module Rails
9
4
  module Surrender
10
5
  # Additions to the Rails ActionController to allow surrender's rendering.
@@ -14,36 +9,28 @@ module Rails
14
9
  super
15
10
  end
16
11
 
17
- def surrender(resource, status: 200, reload: true, include: [], exclude: [])
18
- resource = filter resource if parsed_query_params.filter?
19
-
20
- if parsed_query_params.sort?
21
- resource = sort resource
22
- response.headers['X-Sort'] = parsed_query_params.sort.request
12
+ def surrender(resource, status: 200, include: [], exclude: [], &)
13
+ # Before the selection, which would parse and check the other asks a menu ignores.
14
+ if Surrender.menu_param.asked_in?(query_params)
15
+ render_endpoint_menu(resource, include: include, exclude: exclude)
16
+ else
17
+ render_selected(resource, status: status, include: include, exclude: exclude, &)
23
18
  end
19
+ end
24
20
 
25
- if paginate?(resource)
26
- resource = paginate resource
27
- response.headers['X-Pagination'] = pagination_headers(resource)
28
- end
21
+ private
29
22
 
30
- surrender_response = if parsed_query_params.count?
31
- Render::Count.new(resource).parse
32
- elsif parsed_query_params.ids?
33
- Render::Ids.new(resource).parse
34
- else
35
- config = Render::Configuration.new(
36
- resource_class: resource_class(resource),
37
- reload_resource: reload,
38
- user_exclude: parsed_query_params.exclude,
39
- user_include: parsed_query_params.include,
40
- ctrl_exclude: exclude,
41
- ctrl_include: include
42
- )
23
+ def render_selected(resource, status:, include:, exclude:)
24
+ selection = Selection.new(query_params, paginate: @will_paginate)
25
+ selected = selection.apply(resource)
26
+ response.headers.merge!(selected.headers)
43
27
 
44
- Render::Resource.new(resource: resource,
45
- ability: ability,
46
- config: config).parse
28
+ surrender_response = if selection.count?
29
+ Response.new(data: { count: selected.count })
30
+ else
31
+ asks = { include: query_params[:include], exclude: query_params[:exclude],
32
+ controller_include: include, controller_exclude: exclude }
33
+ Render::Resource.new(resource: selected.records, ability: ability, asks: asks).parse
47
34
  end
48
35
 
49
36
  # Allows the calling method to decorate the response data before returning the result
@@ -52,57 +39,25 @@ module Rails
52
39
  render(json: surrender_response.json_data, status: status)
53
40
  end
54
41
 
55
- private
42
+ # Never decorated by the block, so every endpoint's menu has the same shape.
43
+ def render_endpoint_menu(resource, include:, exclude:)
44
+ menu = EndpointMenu.new(resource, include: include, exclude: exclude, paginate: @will_paginate)
45
+ render(json: Response.new(data: menu.as_json).json_data)
46
+ end
56
47
 
57
48
  def ability
58
- return current_ability if respond_to?(:current_ability)
49
+ # Apps commonly override CanCanCan's current_ability as a private method.
50
+ return current_ability if respond_to?(:current_ability, true)
59
51
 
60
52
  DefaultAbility.new
61
53
  end
62
54
 
63
- def resource_class(resource)
64
- resource.try(:klass) || resource.class
65
- end
66
-
67
55
  def skip_pagination
68
56
  @will_paginate = false
69
57
  end
70
58
 
71
- def filter(resource)
72
- FilterBuilder.new(resource: resource, filter: parsed_query_params.filter).build!
73
- end
74
-
75
- def paginate?(resource)
76
- pagination(resource).paginatable? && @will_paginate
77
- end
78
-
79
- def paginate(resource)
80
- pagination(resource).build!
81
- end
82
-
83
- def pagination(resource)
84
- PaginationBuilder.new(resource: resource, pagination: parsed_query_params.pagination)
85
- end
86
-
87
- def pagination_headers(resource)
88
- {
89
- total: resource.total_count,
90
- page_total: resource.count,
91
- page: resource.current_page,
92
- previous_page: resource.prev_page,
93
- next_page: resource.next_page,
94
- last_page: resource.total_pages,
95
- per_page: parsed_query_params.pagination.per,
96
- offset: resource.offset_value
97
- }.to_json
98
- end
99
-
100
- def sort(resource)
101
- SortBuilder.new(resource: resource, sort: parsed_query_params.sort).build!
102
- end
103
-
104
- def parsed_query_params
105
- @parsed_query_params ||= QueryParamParser.new(request.query_parameters.symbolize_keys)
59
+ def query_params
60
+ request.query_parameters.symbolize_keys
106
61
  end
107
62
  end
108
63
  end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ module Fields
6
+ # What a request and a controller ask one level of the tree to include and exclude. Each list holds bare names,
7
+ # and hashes that carry the asks for the level below, such as { 'author' => ['name'] }.
8
+ Asks = Data.define(:request_include, :request_exclude, :controller_include, :controller_exclude) do
9
+ def initialize(request_include: [], request_exclude: [], controller_include: [], controller_exclude: [])
10
+ super(request_include: listed(request_include), request_exclude: listed(request_exclude),
11
+ controller_include: listed(controller_include), controller_exclude: listed(controller_exclude))
12
+ end
13
+
14
+ def request_includes
15
+ names_in(request_include)
16
+ end
17
+
18
+ def controller_includes
19
+ names_in(controller_include)
20
+ end
21
+
22
+ # A request's include wins over any exclude. `author:[name]` excludes the author's name, not the author, so
23
+ # only bare names exclude at this level.
24
+ def excludes?(name)
25
+ return false if request_includes.include?(name)
26
+
27
+ (request_exclude + controller_exclude).grep_v(Hash).map(&:to_sym).include?(name)
28
+ end
29
+
30
+ def below(name)
31
+ self.class.new(**to_h.transform_values { |list| asks_below(list)[name] })
32
+ end
33
+
34
+ private
35
+
36
+ def listed(list)
37
+ (list.is_a?(Array) ? list : [list]).compact
38
+ end
39
+
40
+ def names_in(list)
41
+ list.flat_map { |item| item.is_a?(Hash) ? item.keys : item }.map(&:to_sym).uniq
42
+ end
43
+
44
+ def asks_below(list)
45
+ list.grep(Hash).reduce({}, :merge).transform_keys(&:to_sym)
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ module Fields
6
+ # A field rendered as the value its record returns for it. Its type is the Rails type of the attribute, such as
7
+ # :string or :datetime, or nil for a method the model defines.
8
+ Attribute = Data.define(:name, :type) do
9
+ # Every record leads with its id, wherever the model or the asks list it.
10
+ def rank
11
+ name == :id ? 0 : 1
12
+ end
13
+
14
+ def preload; end
15
+
16
+ def circular?(_above)
17
+ false
18
+ end
19
+
20
+ def branch(**); end
21
+
22
+ def menu(**); end
23
+
24
+ def write(record, into:, **)
25
+ into[name] = record.public_send(name)
26
+ end
27
+
28
+ def describe(_branch)
29
+ :attribute
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rails
4
+ module Surrender
5
+ module Fields
6
+ # A field that names an association and renders as the nested resource, with the fields of its branch.
7
+ Expand = Data.define(:name, :reflection) do
8
+ def rank
9
+ 3
10
+ end
11
+
12
+ # The JSON shape it renders as: an array of records for a collection, or one record.
13
+ def type
14
+ reflection.collection? ? :array : :object
15
+ end
16
+
17
+ def preload
18
+ name
19
+ end
20
+
21
+ # Surrender never renders a model inside itself, and STI subclasses count as their base class.
22
+ def circular?(above)
23
+ target.base_class.in?(above)
24
+ end
25
+
26
+ def branch(asks:, above:)
27
+ Node.new(target, asks.below(name), above + [target.base_class])
28
+ end
29
+
30
+ def menu(asks:, above:)
31
+ FieldMenu.new(target, asks: asks.below(name), above: above + [target.base_class])
32
+ end
33
+
34
+ # The record at the top is never checked against the ability, only the records nested in it. A nested record
35
+ # the ability can't read renders as nil, like a missing one, so every field the menu lists keeps its key.
36
+ def write(record, into:, ability:, branch:)
37
+ value = record.public_send(name)
38
+
39
+ into[name] = if reflection.collection?
40
+ value.select { |nested| ability.can?(:read, nested) }
41
+ .map { |nested| branch.for(nested.class).render(nested, ability) }
42
+ elsif value && ability.can?(:read, value)
43
+ branch.for(value.class).render(value, ability)
44
+ end
45
+ end
46
+
47
+ def describe(branch)
48
+ branch.to_h
49
+ end
50
+
51
+ private
52
+
53
+ # A polymorphic association has no class until a record loads, but the tree is worked out before any do.
54
+ def target
55
+ if reflection.polymorphic?
56
+ raise ArgumentError,
57
+ "surrender can't expand the polymorphic association #{reflection.active_record}##{name}"
58
+ end
59
+
60
+ reflection.klass
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end