verquest 0.7.1 → 0.9.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a8cd5618a10d4cd2445bfaa83544c67b1b2875aaf4c2a81f4f379c58b542fa48
4
- data.tar.gz: d6f5d4e461d21ea2ddbe00d0a5e1ecae6846807359b39d4af0deb17b53c353a5
3
+ metadata.gz: fd6f2a0f230e6345a0e63458644937161ee4c2fe631d3d8112c1a9ba559220fc
4
+ data.tar.gz: 64c65c15ee3bb1a7b1bd4f5c93778bae79a154ae86502dc143298db85db6c4ce
5
5
  SHA512:
6
- metadata.gz: 47f7a89e151551c01db83182d160af65ce0087eac9c9b98968f166c0bd6583fbd04308b8cd12dbf0a7fa037802a2858e464763002b74d12ae7675ec47ab928fd
7
- data.tar.gz: c9fea3cbebb730cd85757067b9f5b1ca7aa31893c61e617e05d6e1757dea57cd226a686cc8c43949c7bb5ca49babb6ee2b6546875a82e1286859fe6466da5bda
6
+ metadata.gz: d5e340359033758d79e228543e7b070a4aff9ef0d4026b695ec8c418527e8a476582b674deb8a74892ff328541e5a34ea0667e32b83d5dbb0f4c64ba182663c4
7
+ data.tar.gz: dec4b9a1337c8d8656fbc6b1cb799155d208c20f86fa0a4b4ec605ef10ed32b90b247818137ee4b60d54ba5fa0e1b570be7aad0fe1d13db45eabc798ba73d130
data/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.9.0] - 2026-11-09
4
+
5
+ ### Added
6
+ - `filter` declares a property with `field`, `array` or `enum` (`as:`) and the block that filters by its value; `apply_filters(target, params, version:)` runs a version's filters in declaration order, skipping nil and empty values, and `filter_names(version:)` lists them. Filters are inherited, excluded and replaced with their properties. A filter with `map:`, another `as:`, no block, or outside a version's root raises `Verquest::DefinitionError`.
7
+ - `process(..., reject_other_version_keys: true)` (or `config.reject_other_version_keys`) reports root keys that only another version declares as validation errors of type `other_version`, when params are validated.
8
+
9
+ ### Changed
10
+ - Validation skips json_schemer's default insertion when the schema declares no `default`, which makes `process` about 15% faster for such schemas.
11
+
12
+ ### Fixed
13
+ - `process` no longer inserts defaults into the caller's nested hashes, and no longer raises `FrozenError` for frozen nested params when it inserts defaults.
14
+
15
+ ## [0.8.0] - 2026-11-06
16
+
17
+ ### Changed
18
+ - **Breaking:** `enum` writes a `type` next to its values and checks the values when the request is defined. Without `type:`, the type is inferred: Strings are `string`, Integers `integer`, other Numerics `number`, `true`/`false` `boolean`, Hashes `object`; Integers next to other Numerics are `number`, and other mixes a type array. These now raise `ArgumentError`:
19
+ - a value of another class, such as a Symbol (Symbols never matched JSON values) or an Array;
20
+ - `nil` in the values without `nullable: true`;
21
+ - a `type:` other than the five above, or one a value doesn't fit;
22
+ - values equal in JSON, such as `1` and `1.0` (also inside Hashes);
23
+ - NaN or Infinity;
24
+ - `values:` that isn't an Array;
25
+ - a Hash value with a key that isn't a String, or with something inside that isn't JSON (such as a Symbol).
26
+
27
+ `nullable: true` adds `"null"` to the type, inferred or given. `with_options(type:)` no longer applies to enums.
28
+ - With `json_schema_version = :openapi30`, documents (`to_schema` and `to_parameters`) use OpenAPI 3.0 forms: `nullable: true` instead of a `"null"` type, an `anyOf` of single types (each nullable) instead of a type array, a nullable constant as an `enum` with `null`, an `allOf` around a nullable `$ref` or discriminated `one_of`, and `x-dependentRequired` instead of `dependentRequired`. Validation schemas keep the JSON Schema forms validators honour.
29
+ - Under `:openapi30`, `valid_schema?` and `validate_schema` check the document (`to_schema`) instead of the validation schema, whose JSON Schema forms made the check fail for any nullable request.
30
+ - Schemas leave out `required` when nothing is required, instead of an empty array, which draft 4 and OpenAPI 3.0 forbid. Validation is unchanged. `present` and `absent` without a property name raise `ArgumentError`.
31
+
32
+ ### Fixed
33
+ - Query params convert `""` to `nil` in nullable string and mixed enums, and in nullable fields with `enum:`.
34
+
3
35
  ## [0.7.1] - 2026-11-06
4
36
 
5
37
  ### Added
data/README.md CHANGED
@@ -20,7 +20,7 @@ Sponsored by [Stora](https://stora.co)
20
20
 
21
21
  - [Installation](#installation)
22
22
  - [Quick Start](#quick-start)
23
- - [Core Features](#core-features): [schema definition](#schema-definition-and-validation), [oneOf](#oneof), [conditional schemas](#conditional-schemas), [custom field types](#custom-field-types), [versioning](#versioning), [mapping](#mapping-request-structure), [query parameters](#query-parameters), [path parameters](#path-parameters), [OpenAPI components](#component-generation-for-openapi)
23
+ - [Core Features](#core-features): [schema definition](#schema-definition-and-validation), [oneOf](#oneof), [conditional schemas](#conditional-schemas), [custom field types](#custom-field-types), [versioning](#versioning), [mapping](#mapping-request-structure), [query parameters](#query-parameters), [filters](#filters), [path parameters](#path-parameters), [OpenAPI components](#component-generation-for-openapi)
24
24
  - [Rails and rswag](docs/rails.md)
25
25
  - [Configuration](#configuration)
26
26
 
@@ -29,7 +29,7 @@ Sponsored by [Stora](https://stora.co)
29
29
  Add this line to your application's Gemfile:
30
30
 
31
31
  ```ruby
32
- gem "verquest", "~> 0.7"
32
+ gem "verquest", "~> 0.9"
33
33
  ```
34
34
 
35
35
  And then execute:
@@ -134,7 +134,8 @@ error.errors
134
134
  Set `config.current_version` to drop the `version:` argument, or `config.validation_error_handling = :result` to get a `Verquest::Result` instead of an exception (see [Configuration](#configuration)). For query and path parameters in controllers, see [Rails and rswag](docs/rails.md).
135
135
 
136
136
  ### JSON schema for OpenAPI
137
- You can generate JSON Schema for your versioned requests, which can be used for API documentation:
137
+
138
+ `to_schema` returns the JSON Schema of a version for your API documentation. References stay `$ref`s:
138
139
 
139
140
  ```ruby
140
141
  UserCreateRequest.to_schema(version: "2025-06")
@@ -161,31 +162,33 @@ Output:
161
162
  "name" => {"type" => "string", "description" => "Name of the permission"},
162
163
  "read" => {"type" => "boolean", "description" => "Permission to read"},
163
164
  "write" => {"type" => "boolean", "description" => "Permission to write"}
164
- }
165
+ },
166
+ "additionalProperties" => false
165
167
  },
166
168
  "description" => "Permissions associated with the user"
167
169
  },
168
170
  "role" => {
171
+ "type" => "string",
169
172
  "enum" => ["member", "manager"],
170
173
  "default" => "member",
171
174
  "description" => "Role of the user"
172
175
  },
173
176
  "profile_details" => {
174
177
  "type" => "object",
175
- "required" => [],
176
178
  "properties" => {
177
179
  "bio" => {"type" => "string", "description" => "Short biography of the user"},
178
180
  "hobbies" => {"type" => "array", "items" => {"type" => "string"}, "description" => "Tags associated with the user"},
179
181
  "social_links" => {
180
182
  "type" => "object",
181
- "required" => [],
182
183
  "properties" => {
183
184
  "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
184
185
  "mastodon" => {"type" => "string", "format" => "uri", "description" => "Mastodon profile URL"}
185
186
  },
187
+ "additionalProperties" => false,
186
188
  "description" => "Some social networks"
187
189
  }
188
- }
190
+ },
191
+ "additionalProperties" => false
189
192
  },
190
193
  "company" => {"const" => "Awesome Inc."}
191
194
  },
@@ -195,7 +198,7 @@ Output:
195
198
 
196
199
  ### JSON schema for validation
197
200
 
198
- You can check the validation JSON schema for a specific version of your request:
201
+ `to_validation_schema` returns the schema that `process` validates against, with references inlined:
199
202
 
200
203
  ```ruby
201
204
  UserCreateRequest.to_validation_schema(version: "2025-06")
@@ -211,7 +214,7 @@ Output:
211
214
  "first_name" => {"type" => "string", "description" => "The first name of the user", "maxLength" => 50},
212
215
  "last_name" => {"type" => "string", "description" => "The last name of the user", "maxLength" => 50},
213
216
  "email" => {"type" => "string", "format" => "email", "description" => "The email address of the user"},
214
- "birth_date" => {"type" => "string", "format" => "date", "description" => "The birth date of the user"},
217
+ "birth_date" => {"type" => ["string", "null"], "format" => "date", "description" => "The birth date of the user"},
215
218
  "address" => { # from the AddressCreateRequest
216
219
  "type" => "object",
217
220
  "description" => "Address Create Request",
@@ -232,37 +235,41 @@ Output:
232
235
  "name" => {"type" => "string", "description" => "Name of the permission"},
233
236
  "read" => {"type" => "boolean", "description" => "Permission to read"},
234
237
  "write" => {"type" => "boolean", "description" => "Permission to write"}
235
- }
238
+ },
239
+ "additionalProperties" => false
236
240
  },
237
241
  "description" => "Permissions associated with the user"
238
242
  },
239
243
  "role" => {
244
+ "type" => "string",
240
245
  "enum" => ["member", "manager"],
241
246
  "default" => "member",
242
247
  "description" => "Role of the user"
243
248
  },
244
- "profile_details" => {"type" => "object",
245
- "required" => [],
249
+ "profile_details" => {
250
+ "type" => "object",
246
251
  "properties" => {
247
252
  "bio" => {"type" => "string", "description" => "Short biography of the user"},
248
253
  "hobbies" => {"type" => "array", "items" => {"type" => "string"}, "description" => "Tags associated with the user"},
249
254
  "social_links" => {
250
- "type" => "object",
251
- "required" => [],
255
+ "type" => "object",
252
256
  "properties" => {
253
- "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
257
+ "github" => {"type" => "string", "format" => "uri", "description" => "GitHub profile URL"},
254
258
  "mastodon" => {"type" => "string", "format" => "uri", "description" => "Mastodon profile URL"}
255
- },
256
- "description" => "Some social networks"}
259
+ },
260
+ "additionalProperties" => false,
261
+ "description" => "Some social networks"
262
+ }
257
263
  },
258
- "company" => {"const" => "Awesome Inc."}
259
- }
264
+ "additionalProperties" => false
265
+ },
266
+ "company" => {"const" => "Awesome Inc."}
260
267
  },
261
268
  "additionalProperties" => false
262
269
  }
263
270
  ```
264
271
 
265
- You can also validate it to ensure it meets the JSON Schema standards:
272
+ `valid_schema?` and `validate_schema` check the validation schema against the meta-schema of `config.json_schema_version`. Under `:openapi30`, they check the `to_schema` document instead, because validation schemas keep JSON Schema forms that OpenAPI 3.0 forbids:
266
273
 
267
274
  ```ruby
268
275
  UserCreateRequest.valid_schema?(version: "2025-06") # => true/false
@@ -280,7 +287,7 @@ The JSON schema can be used for both validation of incoming parameters and for g
280
287
  #### Component types
281
288
 
282
289
  - `field`: a scalar value (string, integer, boolean, etc.).
283
- - `enum`: a value from a fixed list.
290
+ - `enum`: a value from a fixed list. Its `type` is inferred from the values (`string`, `integer`, `number`, `boolean`, `object`, or a type array for mixed values) unless you pass `type:`, and every value must fit it. A value of another class (such as a Symbol), `nil` without `nullable: true`, or values equal in JSON (`1` and `1.0`) raise `ArgumentError`.
284
291
  - `object`: a JSON object with its own properties.
285
292
  - `array`: a JSON array of scalar items.
286
293
  - `collection`: a JSON array of objects, defined inline or with `item:` pointing at another request.
@@ -333,17 +340,29 @@ Will produce this validation schema:
333
340
 
334
341
  You can define nullable properties in your request schema by setting the `nullable` option to `true`. This feature is based on the latest JSON Schema specification, which is also used in OpenAPI 3.1.
335
342
 
336
- Nullable enums include Ruby `nil` in their allowed values, which exports as JSON `null`, not the string `"null"`. This also applies to fields with an `enum:` constraint (including custom field types). The supplied values array is not modified.
343
+ Nullable enums include Ruby `nil` in their allowed values, which exports as JSON `null`, not the string `"null"`, and add `"null"` to the type, inferred or given. An enum that lists `nil` itself needs `nullable: true`. This also applies to fields with an `enum:` constraint (including custom field types). The supplied values array is not modified.
337
344
 
338
345
  ```ruby
339
346
  enum :role, values: %w[member admin], nullable: true
340
- # => {"role" => {"enum" => ["member", "admin", nil]}}
347
+ # => {"role" => {"type" => ["string", "null"], "enum" => ["member", "admin", nil]}}
348
+ # under :openapi30: {"type" => "string", "nullable" => true, "enum" => ["member", "admin", nil]}
341
349
 
342
350
  const :kind, value: "user", nullable: true
343
351
  # => {"kind" => {"anyOf" => [{"const" => "user"}, {"type" => "null"}]}}
344
352
  ```
345
353
 
346
- Nullable constants and references use `anyOf` with a null alternative in both exported and validation schemas. Nullable `one_of` uses an outer `anyOf` around the original `oneOf` and the null alternative. This allows null even when a referenced schema or multiple variants already accept it, while preserving all restrictions on non-null values. A discriminator, when present, stays alongside the inner `oneOf`.
354
+ Nullable constants and references use `anyOf` with a null alternative in both exported and validation schemas (except `:openapi30` documents, see below). Nullable `one_of` uses an outer `anyOf` around the original `oneOf` and the null alternative. This allows null even when a referenced schema or multiple variants already accept it, while preserving all restrictions on non-null values. A discriminator, when present, stays alongside the inner `oneOf`.
355
+
356
+ OpenAPI 3.0 has no `null` type, so with `json_schema_version = :openapi30` documents (`to_schema` and `to_parameters`) write `nullable: true` instead:
357
+ - next to the type;
358
+ - merged into a nullable constant (with `null` in its `enum`) or a `one_of` without a discriminator;
359
+ - next to an `allOf` around a nullable reference (`{"allOf" => [{"$ref" => "..."}], "nullable" => true}`) or a nullable `one_of` with a discriminator, which keeps null outside the discriminated `oneOf`, as versponse does.
360
+
361
+ OpenAPI 3.0 also has no `dependentRequired` (from `required: [:other]`), so documents write it as the `x-dependentRequired` extension. Validation still enforces it.
362
+
363
+ Mixed types become an `anyOf` of single types, each nullable when the property is. Strict OpenAPI 3.0.3 tools honour `nullable` only next to `type`, so they may still treat a nullable reference or `one_of` as not nullable. Validation schemas keep the forms above, which validators honour.
364
+
365
+ Enum values must be JSON values: Strings, Numerics, booleans or Hashes, given as an Array. Hash values need String keys, and everything inside them must be JSON too (Strings, finite numbers, booleans, `nil`, Arrays and Hashes). A BigDecimal or Rational value is a `number`, but Ruby's JSON generator writes it as a string, so prefer Integers and Floats in documented enums.
347
366
 
348
367
  `required: true` still requires the key to be present; `nullable: true` only permits its value to be null. Defaults stay on the outer nullable schema so missing properties still receive them when default insertion is enabled. Explicit null values are not replaced by defaults.
349
368
 
@@ -378,15 +397,13 @@ Will produce this validation schema:
378
397
  {
379
398
  "type" => "object",
380
399
  "description" => "This is a simple request with nullable properties for testing purposes.",
381
- "required" => [],
382
400
  "properties" => {
383
401
  "array" => {"type" => %w[array null], "items" => {"type" => "string"}},
384
402
  "collection_with_item" => {"type" => %w[array null], "items" => {"type" => "object", "description" => "This is an another example for testing purposes.", "required" => %w[simple_field nested], "properties" => {"simple_field" => {"type" => "string", "description" => "The simple field"}, "nested" => {"type" => "object", "required" => %w[nested_field_1 nested_field_2], "properties" => {"nested_field_1" => {"type" => "string", "description" => "This is a nested field"}, "nested_field_2" => {"type" => "string", "description" => "This is another nested field"}}, "additionalProperties" => false}}, "additionalProperties" => false}},
385
- "collection_with_object" => {"type" => %w[array null], "items" => {"type" => "object", "required" => [], "properties" => {"field" => {"type" => "string"}}, "additionalProperties" => false}},
403
+ "collection_with_object" => {"type" => %w[array null], "items" => {"type" => "object", "properties" => {"field" => {"type" => "string"}}, "additionalProperties" => false}},
386
404
  "field" => {"type" => %w[string null]},
387
405
  "object" => {
388
406
  "type" => %w[object null],
389
- "required" => [],
390
407
  "properties" => {
391
408
  "field" => {"type" => "string"}
392
409
  },
@@ -607,7 +624,6 @@ end
607
624
  {
608
625
  "type" => "object",
609
626
  "description" => "User Create Request",
610
- "required" => ["email"],
611
627
  "properties" => {
612
628
  "email" => {
613
629
  "type" => "string",
@@ -670,9 +686,8 @@ class UserCreateRequest < Verquest::Base
670
686
  end
671
687
  ```
672
688
 
673
- Internal `Verquest::VersionResolver` is then used to resolve the right version for the one specified in the call. It implements a "downgrading" strategy - when an exact version match isn't found, it returns the closest earlier version.
689
+ `Verquest::VersionResolver` picks the version block for the requested version. When no block matches exactly, it picks the closest earlier one:
674
690
 
675
- Example:
676
691
  ```ruby
677
692
  UserCreateRequest.process(params, version: "2025-05") # => use the defined version "2025-04"
678
693
  UserCreateRequest.process(params, version: "2025-06") # => use the defined version "2025-06"
@@ -681,9 +696,9 @@ UserCreateRequest.process(params, version: "2025-08") # => use the defined versi
681
696
  UserCreateRequest.process(params, version: "2025-10") # => use the closest earlier version "2025-08"
682
697
  ```
683
698
 
684
- This is used across all referenced requests, so if you have a `UserRequest` that references an `AddressCreateRequest`, it will also resolve the correct version of the `AddressCreateRequest` based on the initial requested version (as the `AddressCreateRequest` can have different versions defined).
699
+ References resolve the same way. When `UserCreateRequest` references `AddressCreateRequest`, the requested version also picks the `AddressCreateRequest` block, so the two classes can declare different versions.
685
700
 
686
- The goal here is to avoid redefining the same request structure in multiple versions when there are no changes, and to facilitate the easy evolution of API requests over time. When a new API version is created and there are no changes to the requests, you don't need to update anything.
701
+ A new API version that doesn't change a request needs no new `version` block in it.
687
702
 
688
703
  #### Supported versions
689
704
 
@@ -713,13 +728,11 @@ OverlockRequest.process(params, version: "2026-06") # => raises Verquest::Versio
713
728
 
714
729
  ### Mapping request structure
715
730
 
716
- Verquest's mapping system allows transforming external API request structures into your internal application data structures.
717
-
718
- Here’s a short example: we store the address in the same table as the user internally, but the API request structure is different.
731
+ `map:` turns the public request structure into the structure your app uses. In this example, the app stores the address in the users table, so the address fields move to the root:
719
732
 
720
733
  ```ruby
721
734
  class UserCreateRequest < Verquest::Base
722
- version "2025-06", exclude_properties: %i[street city] do
735
+ version "2025-06" do
723
736
  field :full_name, type: :string, map: "name"
724
737
  field :email, type: :string, format: "email", required: true
725
738
  field :phone, type: :string
@@ -733,40 +746,43 @@ class UserCreateRequest < Verquest::Base
733
746
  end
734
747
  ```
735
748
 
736
- When called with `UserCreateRequest.process(params)`, the `address` object will be mapped to the internal structure with keys `address_street`, `address_city`, and `address_zip`.
749
+ `UserCreateRequest.process` turns these params:
737
750
 
738
- Example request params
739
751
  ```ruby
740
752
  {
741
- "full_name": "John Doe",
742
- "email": "john@doe.com",
743
- "phone": "1234567890",
744
- "address": {
745
- "street": "123 Main St",
746
- "city": "Springfield",
747
- "postal_code": "12345"
753
+ "full_name" => "John Doe",
754
+ "email" => "john@doe.com",
755
+ "phone" => "1234567890",
756
+ "address" => {
757
+ "street" => "123 Main St",
758
+ "city" => "Springfield",
759
+ "postal_code" => "12345"
748
760
  }
749
761
  }
750
762
  ```
751
763
 
752
- Will be transformed to:
764
+ into:
765
+
753
766
  ```ruby
754
767
  {
755
- "name": "John Doe",
756
- "email": "john@doe.com",
757
- "phone": "1234567890",
758
- "address_street": "123 Main St",
759
- "address_city": "Springfield",
760
- "address_zip": "12345"
768
+ "name" => "John Doe",
769
+ "email" => "john@doe.com",
770
+ "phone" => "1234567890",
771
+ "address_street" => "123 Main St",
772
+ "address_city" => "Springfield",
773
+ "address_zip" => "12345"
761
774
  }
762
775
  ```
763
776
 
764
- What you can use:
765
- - `/` to reference the root of the request structure
766
- - `nested/structure` use slash notation to reference nested structures
767
- - if the `map` is not set, the field name will be used as the key in the internal structure
777
+ `map:` takes one of these forms:
768
778
 
769
- To get the mapping to map the request structure back to the external API structure, you can use the `external_mapping` method:
779
+ - `"name"`: a key at the same level;
780
+ - `"/name"`: a key at the root;
781
+ - `"nested/structure"`: a key inside nested objects.
782
+
783
+ Without `map:`, the property name is the key.
784
+
785
+ `external_mapping` returns the mapping back, from internal keys to external paths:
770
786
 
771
787
  ```ruby
772
788
  UserCreateRequest.external_mapping(version: "2025-06")
@@ -799,12 +815,20 @@ class DealsIndexQuery < Verquest::Base
799
815
  field :page, type: :integer, minimum: 1, default: 1
800
816
  field :archived, type: :boolean
801
817
  enum :sort_direction, values: %w[ASC DESC], default: "DESC"
802
- array :status, type: :string, explode: false, item_schema_options: {enum: %w[open won lost]}
818
+ filter :status, as: :array, type: :string, explode: false, item_schema_options: {enum: %w[open won lost]} do |deals, value|
819
+ deals.where(status: value)
820
+ end
803
821
 
804
822
  object :created do # sent as created[after]=...
805
823
  field :after, type: :string, format: "date-time", map: "/created_after"
806
824
  end
807
825
  end
826
+
827
+ version "2025-08" do # inherits the 2025-06 properties and filters
828
+ filter :site_id, type: :string do |deals, value|
829
+ deals.where(site_id: value)
830
+ end
831
+ end
808
832
  end
809
833
 
810
834
  DealsIndexQuery.process(request.query_parameters, version: "2025-06")
@@ -812,8 +836,10 @@ DealsIndexQuery.process(request.query_parameters, version: "2025-06")
812
836
  # => {"page" => 2, "archived" => true, "sort_direction" => "DESC", "status" => ["open", "won"], "created_after" => "2025-01-01T00:00:00Z"}
813
837
  ```
814
838
 
839
+ `filter :status, as: :array` declares the same property as `array :status`, plus a block that [Filters](#filters) describes.
840
+
815
841
  Conversion follows the validation schema:
816
- - `integer` and `number` from digits (`"2"`, `"-1.5"`), `boolean` from `"true"` and `"false"`, `null` from an empty string when the schema allows it;
842
+ - `integer` and `number` from digits (`"2"`, `"-1.5"`), `boolean` from `"true"` and `"false"`, `null` from an empty string when the schema allows it (a string outside an enum's values tries the next type, so `""` is `nil` in a nullable string enum);
817
843
  - arrays split on commas with `explode: false` (`status=open,won`), or come from repeated keys with `explode: true` (`status[]=open&status[]=won`; Rails keeps only the last value of a plain repeated key). `config.query_array_explode` sets the default (`true`);
818
844
  - objects (`deepObject`, one level deep) convert each property.
819
845
 
@@ -837,6 +863,36 @@ array :status, type: :string, explode: false, item_schema_options: {enum: %w[ope
837
863
 
838
864
  A property reference to another query class reuses its definition, e.g. a shared `expand` parameter: `reference :expand, from: ExpandQuery, property: :expand`.
839
865
 
866
+ ### Filters
867
+
868
+ `filter` declares a property and the block that filters by its value. The property is a `field` by default, an `array` with `as: :array`, or an `enum` with `as: :enum`, in a body or a query request. `apply_filters` passes the target through the version's filters in declaration order, and skips a filter when its value is nil or empty. `DealsIndexQuery` from [Query parameters](#query-parameters) filters by `status` from `2025-06`, and also by `site_id` from `2025-08`:
869
+
870
+ ```ruby
871
+ params = DealsIndexQuery.process(request.query_parameters, version: "2025-08")
872
+ DealsIndexQuery.apply_filters(Deal.all, params, version: "2025-08")
873
+ DealsIndexQuery.filter_names(version: "2025-08") # => ["status", "site_id"]
874
+ ```
875
+
876
+ - Filters follow the rules of properties. A later version inherits them, `exclude_properties` removes one, and redeclaring a filter replaces its block. Redeclaring it as a plain property, such as `field :status`, stops it filtering.
877
+ - `reference` copies the property without its filter.
878
+ - The block runs only from `apply_filters`, with `self` set to the request class.
879
+ - `apply_filters` reads the params by their String names, as `process` returns them. With `validation_error_handling = :result`, pass the result's `value`.
880
+ - A filter must be at the root of a version, and it can't use `map:`. Otherwise defining the version raises `Verquest::DefinitionError`.
881
+
882
+ [`test/support/examples/deals_index_query.rb`](test/support/examples/deals_index_query.rb) runs the same query against an Array of Hashes.
883
+
884
+ #### Reject keys from other versions
885
+
886
+ `process` drops root keys that the version doesn't declare. A client that sends `site_id` to `2025-06` gets an unfiltered list and no error. With `reject_other_version_keys: true`, `process` reports a root key that only another version declares as a validation error:
887
+
888
+ ```ruby
889
+ DealsIndexQuery.process({"site_id" => "site_1"}, version: "2025-06", reject_other_version_keys: true)
890
+ # raises Verquest::InvalidParamsError with
891
+ # [{pointer: "/site_id", type: "other_version", message: "`site_id` isn't available in version 2025-06", details: nil}]
892
+ ```
893
+
894
+ `remove_extra_root_keys` still drops keys that no version declares, such as `utm_source`. The check works for body requests too, and runs only when `process` validates the params. `config.reject_other_version_keys` sets the default (`false`).
895
+
840
896
  ### Path parameters
841
897
 
842
898
  `location :path` works like `location :query`, but documents `in: :path` parameters. Path parameters must be required scalars; arrays, objects, one_of and optional properties raise `Verquest::DefinitionError`.
@@ -891,6 +947,9 @@ Verquest.configure do |config|
891
947
 
892
948
  # Remove extra root keys from provided params
893
949
  config.remove_extra_root_keys = true # default
950
+
951
+ # Report root keys that only another version declares, see Filters
952
+ config.reject_other_version_keys = false # default
894
953
 
895
954
  # Set custom version resolver
896
955
  config.version_resolver = CustomVersionResolver # default is `Verquest::VersionResolver`
data/Rakefile CHANGED
@@ -32,9 +32,10 @@ task :yard do
32
32
  puts "\nYARD documentation: 100% documented"
33
33
  end
34
34
 
35
- desc "Benchmark the transformer (objects allocated and calls per second)"
35
+ desc "Benchmark the transformer and process (objects allocated and calls per second)"
36
36
  task :bench do
37
37
  ruby "-Ilib", "bench/transformer.rb"
38
+ ruby "-Ilib", "bench/process.rb"
38
39
  end
39
40
 
40
41
  task default: %i[test rubocop yard]
data/docs/rails.md CHANGED
@@ -62,7 +62,8 @@ module VerquestParams
62
62
 
63
63
  # Every path class applies, so /deals/:deal_id/notes/:id can check both IDs
64
64
  @path_params = by_location.fetch(:path, []).to_h { |declaration| process_path_param(declaration) }
65
- # Unknown query keys (cache busters, tracking) are dropped instead of rejected
65
+ # Unknown query keys (cache busters, tracking) are dropped instead of rejected. Add
66
+ # `reject_other_version_keys: true` to reject keys from another version, such as a newer filter.
66
67
  @query_params = by_location[:query]&.first&.dig(:class)&.process(request.query_parameters, remove_extra_root_keys: true)
67
68
  @body_params = by_location[:body]&.first&.dig(:class)&.process(request.request_parameters)
68
69
  end
@@ -115,6 +116,10 @@ class DealsController < ApplicationController
115
116
  verquest_params DealsIndexQuery, only: :index
116
117
  verquest_params DealUpdateRequest, only: :update
117
118
 
119
+ def index
120
+ render json: DealsIndexQuery.apply_filters(Deal.all, query_params)
121
+ end
122
+
118
123
  def show
119
124
  render json: Deal.find_by!(public_id: path_params["id"])
120
125
  end
@@ -127,6 +132,8 @@ end
127
132
 
128
133
  `GET /deals/con_123` then returns 422 with `{"pointer" => "/id", ...}`, and `POST /deals/con_123/win` with `{"pointer" => "/deal_id", ...}`.
129
134
 
135
+ `DealsIndexQuery` declares its filters with `filter` (see [Filters](../README.md#filters)). `apply_filters` takes the version from `config.current_version`, like `process`. `GET /2025-06/deals?site_id=site_1` lists every deal, because `site_id` is a `2025-08` filter and `process` drops it. With `reject_other_version_keys: true`, the same request returns 422 with `{"pointer" => "/site_id", "type" => "other_version", ...}`.
136
+
130
137
  ## rswag
131
138
 
132
139
  A shared context documents a query or path class with `to_parameters`. `name:` renames a path class's parameter to the route key, and `description:` replaces its description:
@@ -8,6 +8,9 @@ module Verquest
8
8
  #
9
9
  # @api private
10
10
  module Base::PrivateClassMethods
11
+ # Property methods a filter can declare its property with
12
+ FILTER_PROPERTY_METHODS = %i[field array enum].freeze
13
+
11
14
  # Resolves the version to use, either from the provided version,
12
15
  # configuration's current_version, or raises an error if none is available
13
16
  #
@@ -87,6 +90,18 @@ module Verquest
87
90
  raise VersionNotFoundError, "Version '#{version}' is outside supported_versions (#{range}) of #{name || inspect}"
88
91
  end
89
92
 
93
+ # Copies the hashes and arrays in params, so inserting defaults leaves the caller's params alone
94
+ #
95
+ # @param value [Object] The params or a value inside them
96
+ # @return [Object] A copy of hashes and arrays, other values as they are
97
+ def copy_params(value)
98
+ case value
99
+ when Hash then value.transform_values { |item| copy_params(item) }
100
+ when Array then value.map { |item| copy_params(item) }
101
+ else value
102
+ end
103
+ end
104
+
90
105
  # Defines a new version with optional inheritance from another version
91
106
  #
92
107
  # @param name [String] The name/identifier of the version
@@ -106,6 +121,7 @@ module Verquest
106
121
 
107
122
  @default_options = {}
108
123
  @current_scope = version
124
+ @defining_version = version
109
125
 
110
126
  instance_exec(&block)
111
127
  ensure
@@ -200,7 +216,7 @@ module Verquest
200
216
 
201
217
  required = default_options.fetch(:required, false) if required.nil?
202
218
  nullable = default_options.fetch(:nullable, false) if nullable.nil?
203
- schema_options = default_options.except(:required, :nullable).merge(schema_options)
219
+ schema_options = default_options.except(:type, :required, :nullable).merge(schema_options)
204
220
 
205
221
  enum_property = Properties::Enum.new(name:, values:, map:, required:, nullable:, **schema_options)
206
222
  add_property(enum_property, parameter_examples)
@@ -336,6 +352,37 @@ module Verquest
336
352
  add_property(array, parameter_examples)
337
353
  end
338
354
 
355
+ # Defines a property and the block that filters by its processed value
356
+ #
357
+ # The property is declared with `field`, `array` or `enum` (`as:`), with the other options. The
358
+ # block is stored, not run: {PublicClassMethods#apply_filters} calls it later, and `self` inside it
359
+ # is the request class, so the class's private class methods are available. Filters are inherited,
360
+ # excluded and replaced with their properties.
361
+ #
362
+ # @example
363
+ # filter :status, as: :array, type: :string, explode: false do |target, value|
364
+ # target.where(status: value)
365
+ # end
366
+ #
367
+ # @param name [Symbol] The name of the property
368
+ # @param as [Symbol] `:field` (default), `:array` or `:enum`
369
+ # @param options [Hash] Options for the property method
370
+ # @yieldparam target [Object] What is being filtered, as returned by the previous filter
371
+ # @yieldparam value [Object] The property's processed value, never nil or empty
372
+ # @yieldreturn [Object] The filtered target
373
+ # @return [void]
374
+ # @raise [Verquest::DefinitionError] Without a block, with another `as:`, with `map:`, or outside a version's root
375
+ def filter(name, as: :field, **options, &block)
376
+ label = "Filter '#{name}' in version '#{@defining_version&.name}'"
377
+ raise DefinitionError, "#{label} needs a block that filters the target" unless block
378
+ raise DefinitionError, "#{label} can't be declared as: #{as.inspect}, only as :field, :array or :enum" unless FILTER_PROPERTY_METHODS.include?(as)
379
+ raise DefinitionError, "#{label} can't use map:, apply_filters reads the value by its name" if options.key?(:map)
380
+ raise DefinitionError, "#{label} must be declared at the root of the version, outside object, collection, one_of and conditions" unless current_scope.is_a?(Version)
381
+
382
+ send(as, name, **options)
383
+ current_scope.add_filter(name, block)
384
+ end
385
+
339
386
  # Defines a oneOf property for polymorphic schemas
340
387
  #
341
388
  # Creates a JSON Schema oneOf structure where exactly one of the defined
@@ -366,6 +413,36 @@ module Verquest
366
413
  @current_scope = previous_scope if block_given?
367
414
  end
368
415
 
416
+ # Errors for root keys that only another version declares
417
+ #
418
+ # @param params [Hash] The params being processed
419
+ # @param version [Verquest::Version] The resolved version
420
+ # @return [Array<Hash>] One error per key, in the format of validation errors
421
+ def other_version_key_errors(params, version)
422
+ other_names = versions.property_names - version.all_properties.keys
423
+
424
+ params.keys.filter_map do |key|
425
+ key = key.to_s
426
+ next unless other_names.include?(key)
427
+
428
+ {pointer: "/#{key}", type: "other_version", message: "`#{key}` isn't available in version #{version.name}", details: nil}
429
+ end
430
+ end
431
+
432
+ # Reports failed params according to the validation_error_handling setting
433
+ #
434
+ # @param errors [Array<Hash>] The errors
435
+ # @return [Verquest::Result] A failure, when validation_error_handling is :result
436
+ # @raise [Verquest::InvalidParamsError] When validation_error_handling is :raise
437
+ def validation_failure(errors)
438
+ case Verquest.configuration.validation_error_handling
439
+ when :raise
440
+ raise InvalidParamsError.new("Validation failed", errors:)
441
+ when :result
442
+ Result.failure(errors)
443
+ end
444
+ end
445
+
369
446
  # Adds a property to the current scope
370
447
  #
371
448
  # @param property [Verquest::Properties::Base] The property to add