parameters_schema 0.42 → 1.0.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/Gemfile +3 -3
- data/README.md +286 -286
- data/Rakefile +7 -7
- data/lib/parameters_schema/core_ext.rb +21 -21
- data/lib/parameters_schema/exceptions.rb +23 -23
- data/lib/parameters_schema/options.rb +79 -79
- data/lib/parameters_schema/schema.rb +295 -295
- data/lib/parameters_schema.rb +8 -8
- data/test/helpers.rb +56 -56
- data/test/test_options.rb +74 -74
- data/test/test_schema_allow.rb +114 -114
- data/test/test_schema_allow_empty.rb +29 -29
- data/test/test_schema_allow_nil.rb +33 -33
- data/test/test_schema_hash.rb +90 -90
- data/test/test_schema_required.rb +74 -74
- data/test/test_schema_simple.rb +58 -58
- data/test/test_schema_types.rb +452 -452
- data/test/test_schema_types_complex.rb +126 -126
- metadata +9 -10
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: ab3f9f1e20eec3092c2362e52e002e974c51b2ba
|
4
|
+
data.tar.gz: a9c817c713fa10529286f629d576d5eb09673879
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 68980a8ff4bf48844160bc378a7f572fed2b25c49f6f35ef8f26e667c66dd8a6a0a0cf46559e0624afbe507da3a78c4c8d681540b4ac9ff977ab6ef4e4875a17
|
7
|
+
data.tar.gz: b90a54e7fee674a137305a0c958197b814756f4fe8bfe1fb1e49c95df31d433ca4b10bc2127e52679d50be3bb3a6af4bb3ee3d8c6edbacc85753695a3d46a108
|
data/Gemfile
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
source 'http://rubygems.org'
|
2
|
-
|
3
|
-
gem 'minitest'
|
1
|
+
source 'http://rubygems.org'
|
2
|
+
|
3
|
+
gem 'minitest'
|
4
4
|
gem 'activesupport'
|
data/README.md
CHANGED
@@ -1,286 +1,286 @@
|
|
1
|
-
# Parameters Schema
|
2
|
-
|
3
|
-
## *"A strict API is the best kind of API."*
|
4
|
-
|
5
|
-
In this line of thought, **[strong_parameters](https://github.com/rails/strong_parameters)** lacks
|
6
|
-
|
7
|
-
For example, let's say you want your operation `create` to require a `Fixnum` parameter between 1 and 99. With strong_parameters, you're out of luck. With this gem, you simply write in your controller:
|
8
|
-
``` ruby
|
9
|
-
class Api::PeopleController < Api::BaseController
|
10
|
-
def create
|
11
|
-
validated_params = validate_params params do
|
12
|
-
param :age, type: Fixnum, allow: (1..99)
|
13
|
-
end
|
14
|
-
|
15
|
-
# Do something with the validated parameters.
|
16
|
-
end
|
17
|
-
end
|
18
|
-
```
|
19
|
-
|
20
|
-
So when you use this controller:
|
21
|
-
``` ruby
|
22
|
-
> app.post 'api/people', age: 12 # validated_params = { age: 12 }
|
23
|
-
> app.post 'api/people', age: 100 # throws a ParameterSchema::InvalidParameters
|
24
|
-
```
|
25
|
-
|
26
|
-
## Why use this gem instead of strong_parameters
|
27
|
-
|
28
|
-
* You prefer a procedural approach (via a DSL) over a declarative one.
|
29
|
-
* You want more control over the parameters of your API, at the type and format level.
|
30
|
-
* You want to do things differently, you
|
31
|
-
|
32
|
-
## Installation
|
33
|
-
|
34
|
-
Add in your Gemfile:
|
35
|
-
``` ruby
|
36
|
-
gem 'parameters_schema'
|
37
|
-
```
|
38
|
-
|
39
|
-
Add in your project:
|
40
|
-
``` ruby
|
41
|
-
require 'parameters_schema'
|
42
|
-
```
|
43
|
-
|
44
|
-
## Schema
|
45
|
-
|
46
|
-
The schema is the heart of this gem. It provides a simple DSL to express an operation's parameters.
|
47
|
-
|
48
|
-
Creating a schema:
|
49
|
-
``` ruby
|
50
|
-
schema = ParametersSchema::Schema.new do
|
51
|
-
# Define parameters here...
|
52
|
-
# ... but an empty schema is also valid.
|
53
|
-
end
|
54
|
-
```
|
55
|
-
Validating parameters against a schema:
|
56
|
-
``` ruby
|
57
|
-
params = { potatoe: 'Eramosa' }
|
58
|
-
schema.validate!(params)
|
59
|
-
```
|
60
|
-
|
61
|
-
The minimal representation of a parameter is:
|
62
|
-
``` ruby
|
63
|
-
param :potatoe
|
64
|
-
```
|
65
|
-
This represents a `required` parameter of type `String` accepting any characters and which doesn't allow nil or empty values.
|
66
|
-
|
67
|
-
The valid options for a parameter are:
|
68
|
-
``` ruby
|
69
|
-
* required # Whether the parameter is required. Default: true.
|
70
|
-
* type # The type of the parameter. Default: String.
|
71
|
-
* allow # The allowed values of the parameter. Default: :any.
|
72
|
-
* deny # The denied values of the parameter. Default: :none.
|
73
|
-
* array # Whether the parameter is an array. Default: false.
|
74
|
-
```
|
75
|
-
|
76
|
-
### Parameter types
|
77
|
-
|
78
|
-
The available types are:
|
79
|
-
``` ruby
|
80
|
-
* String
|
81
|
-
* Symbol
|
82
|
-
* Fixnum
|
83
|
-
* Float
|
84
|
-
* Date
|
85
|
-
* DateTime
|
86
|
-
* Array # An array of :any types.
|
87
|
-
* Hash # An object which members are not validated further.
|
88
|
-
* :boolean # See options for accepted values.
|
89
|
-
* :any # Accepts any value type.
|
90
|
-
```
|
91
|
-
|
92
|
-
To accept more than one type, you can do:
|
93
|
-
``` ruby
|
94
|
-
param :potatoe, type: [Boolean, String] # Accepts a boolean or string value.
|
95
|
-
```
|
96
|
-
|
97
|
-
To accept an array of a specific type, you can do:
|
98
|
-
``` ruby
|
99
|
-
param :potatoes, type: { Array => String } # Accepts an array of strings.
|
100
|
-
```
|
101
|
-
|
102
|
-
To deeper refine the schema of an object, you pass a block to the parameter:
|
103
|
-
```
|
104
|
-
param :potatoe do # Implicitly of type Hash
|
105
|
-
param :variety
|
106
|
-
param :origin
|
107
|
-
end
|
108
|
-
```
|
109
|
-
|
110
|
-
As you have seen above, a parameter can be of type `Array` but can also have the option `array`. Confusing, right? This option was introduced to simplify the `type` syntax. For example:
|
111
|
-
```
|
112
|
-
param :potatoes, type: String, array: true # This is equivalent...
|
113
|
-
param :potatoes, type: { Array => String } # ... to this.
|
114
|
-
```
|
115
|
-
|
116
|
-
But this parameter truly shine with an array of objects:
|
117
|
-
```
|
118
|
-
param :potatoes, array: true do
|
119
|
-
param :variety
|
120
|
-
param :origin
|
121
|
-
end
|
122
|
-
|
123
|
-
# This syntax is also valid but less sexy:
|
124
|
-
param :potatoes, type: { Array => Hash } do
|
125
|
-
param :variety
|
126
|
-
param :origin
|
127
|
-
end
|
128
|
-
```
|
129
|
-
|
130
|
-
#### Gotchas
|
131
|
-
* A `Float` value can be passed to a `Fixnum` parameter but will loose its precision.
|
132
|
-
* Some types accepts more than one representation. Example: `Symbol` accepts any type that respond to `:to_sym`.
|
133
|
-
* If you define multiple types (ex: `[Symbol, String]`), values are interpreted in this order. So the value `'a'` will be cast to `:a`.
|
134
|
-
* Defining the type `{ Fixnum => Date }` doesn't make sense so it falls back to `Fixnum` (the key).
|
135
|
-
* `{ Array => Array }` is accepted. It means a 2D array of `:any`.
|
136
|
-
* `{ Array => Array => ... }` is not yet supported. Did I hear pull request?
|
137
|
-
|
138
|
-
### The `allow` and `deny` options
|
139
|
-
|
140
|
-
By default, the value of a parameter can be any one in the spectrum of a type, with the exception of nil and empty. The `allow` and `deny` options can be used to further refine the accepted values.
|
141
|
-
|
142
|
-
To accept nil or empty values:
|
143
|
-
``` ruby
|
144
|
-
param :potatoe, allow: :nil
|
145
|
-
# => accepts nil, 'Kennebec' but not ''.
|
146
|
-
|
147
|
-
param :potatoe, allow: :empty
|
148
|
-
# => accepts '', 'Kennebec' but not nil.
|
149
|
-
|
150
|
-
param :potatoe, allow: [:nil, :empty]
|
151
|
-
# => accepts nil, '' and 'Kennebec'
|
152
|
-
```
|
153
|
-
Of course, this *nil* or *empty* restriction doesn't make sense for all the types so it will only be applied when it does.
|
154
|
-
|
155
|
-
To accept predefined values:
|
156
|
-
``` ruby
|
157
|
-
param :potatoe, allow: ['Superior', 'Ac Belmont', 'Eramosa'] # this is case-sensitive.
|
158
|
-
|
159
|
-
# Gotcha: this will allow empty values even if you wanted to accept the value 'empty'. You can redefine keywords in the options.
|
160
|
-
param :potatoe, type: Symbol, allow: [:superior, :ac_belmont, :empty]
|
161
|
-
```
|
162
|
-
|
163
|
-
To accept a value matching a regex:
|
164
|
-
``` ruby
|
165
|
-
param :potatoe, allow: /^[a-zA-Z]*$/
|
166
|
-
|
167
|
-
# Gotcha: even though the regex above allows empty values, it must be explicitly stated:
|
168
|
-
param :potatoe, allow: [:empty, /^[a-zA-Z]*$/]
|
169
|
-
```
|
170
|
-
|
171
|
-
To accept a value in a range:
|
172
|
-
``` ruby
|
173
|
-
param :potatoe, type: Fixnum, allow: (1..3)
|
174
|
-
# => accepts 1, 2, 3 but will fail on any other value.
|
175
|
-
```
|
176
|
-
|
177
|
-
The `deny` option is conceptually identical to `allow` but a value will fail the validation if a match is found:
|
178
|
-
``` ruby
|
179
|
-
param :potatoe, type: Fixnum, deny: (1..3)
|
180
|
-
# => accepts any value except 1, 2, 3.
|
181
|
-
```
|
182
|
-
|
183
|
-
The options `allow` and `deny` are validated independently. So beware to not define `allow` and `deny` options that encompass all the possible values of the parameter!
|
184
|
-
|
185
|
-
## Exceptions
|
186
|
-
|
187
|
-
When the validation fails, an instance of `ParametersSchema::InvalidParameters` is raised. This exception contains the attribute `errors` which is an hash of `{ key: error_code }` that you can work with.
|
188
|
-
|
189
|
-
Simple case:
|
190
|
-
``` ruby
|
191
|
-
ParametersSchema::Schema.new do
|
192
|
-
param :potatoe
|
193
|
-
end.validate!({})
|
194
|
-
|
195
|
-
# => ParametersSchema::InvalidParameters
|
196
|
-
# @errors = { potatoe: :missing }
|
197
|
-
```
|
198
|
-
|
199
|
-
The validation process tries to accumulate as many errors as possible before raising the exception, so you can have a precise picture of what went wrong:
|
200
|
-
``` ruby
|
201
|
-
ParametersSchema::Schema.new do
|
202
|
-
param :potatoe do
|
203
|
-
param :name
|
204
|
-
param :type, allow: ['Atlantic']
|
205
|
-
end
|
206
|
-
end.validate!(potatoe: { type: 'Conestoga' })
|
207
|
-
|
208
|
-
# => ParametersSchema::InvalidParameters
|
209
|
-
# @errors = { potatoe: { name: :missing, type: :disallowed } }
|
210
|
-
```
|
211
|
-
|
212
|
-
The possible error codes are (in the order the are validated):
|
213
|
-
``` ruby
|
214
|
-
* :unknown # The parameter is provided but not defined in the schema.
|
215
|
-
* :missing # The parameter is required but is missing.
|
216
|
-
* :nil # The value cannot be nil but is nil.
|
217
|
-
* :empty # The value cannot be empty but is empty.
|
218
|
-
* :disallowed # The value has an invalid format (type/allow) other than nil/empty.
|
219
|
-
```
|
220
|
-
|
221
|
-
## Integrate with Rails
|
222
|
-
|
223
|
-
This gem can be used outside of Rails but was created with Rails in mind. For example, the parameters `controller, action, format` are skipped by default (see Options section to override this behavior) and the parameters are defined in a `Hash`. However, this gem doesn't insinuate itself in your project so you must manually add it in your controllers or anywhere else that make sense to you. Here is a little recipe to add validation in your API pipeline:
|
224
|
-
|
225
|
-
In the base controller of your API, add this **helper**:
|
226
|
-
``` ruby
|
227
|
-
# Validate the parameters of an action, using a schema.
|
228
|
-
# Returns the validated parameters and throw exceptions on invalid input.
|
229
|
-
def validate_params(¶meters_schema)
|
230
|
-
schema = ParametersSchema::Schema.new(parameters_schema)
|
231
|
-
schema.validate!(params)
|
232
|
-
end
|
233
|
-
```
|
234
|
-
In the base controller of your API, add this **exception handler**:
|
235
|
-
``` ruby
|
236
|
-
# Handle errors related to invalid parameters.
|
237
|
-
rescue_from ParametersSchema::InvalidParameters do |e|
|
238
|
-
# Do something with the exception (ex: log it).
|
239
|
-
|
240
|
-
# Render the response.
|
241
|
-
render json: ..., status: :bad_request
|
242
|
-
end
|
243
|
-
```
|
244
|
-
|
245
|
-
Now in any controller where you want to validate the parameters, you can do:
|
246
|
-
``` ruby
|
247
|
-
def operation
|
248
|
-
validated_params =
|
249
|
-
# ...
|
250
|
-
end
|
251
|
-
# ...
|
252
|
-
end
|
253
|
-
```
|
254
|
-
|
255
|
-
## Options
|
256
|
-
|
257
|
-
Options can be specified on the module `ParametersSchema::Options`. Example:
|
258
|
-
|
259
|
-
``` ruby
|
260
|
-
ParametersSchema::Options.skip_parameters = [:internal_stuff]
|
261
|
-
```
|
262
|
-
|
263
|
-
Available options:
|
264
|
-
* `skip_parameters` an array of first-level parameters to skip. Default: `[:controller, :action, :format]`.
|
265
|
-
* `empty_keyword` the keyword used to represent an empty value. Default: `:empty`.
|
266
|
-
* `any_keyword` the keyword used to represent any value. Default: `:any`.
|
267
|
-
* `none_keyword` the keyword used to represent no value. Default: `:none`.
|
268
|
-
* `boolean_keyword` the keyword used to represent a boolean value. Default: `:boolean`.
|
269
|
-
* `nil_keyword` the keyword used to represent a nil value. Default: `:nil`.
|
270
|
-
* `boolean_true_values` the accepted boolean true values. Not case-sensitive. Default: `true`, `'t'`, `'true'`, `'1'`, `1`, `1.0`.
|
271
|
-
* `boolean_false_values` the accepted boolean false values. Not case-sensitive. Default: `false`, `'f'`, `'false'`, `'0'`, `0`, `0.0`.
|
272
|
-
|
273
|
-
## Contribute
|
274
|
-
|
275
|
-
Yes, please. Bug fixes, new features, refactoring, unit tests. Send your precious pull requests.
|
276
|
-
|
277
|
-
### Ideas
|
278
|
-
|
279
|
-
* Array of arrays of ...
|
280
|
-
* Min/Max for numeric values
|
281
|
-
* More `allow` options
|
282
|
-
* Better refine error codes
|
283
|
-
|
284
|
-
## License
|
285
|
-
|
286
|
-
Parameters Schema is released under the [MIT License](http://www.opensource.org/licenses/MIT).
|
1
|
+
# Parameters Schema
|
2
|
+
|
3
|
+
## *"A strict API is the best kind of API."*
|
4
|
+
|
5
|
+
In this line of thought, **[strong_parameters](https://github.com/rails/strong_parameters)** lacks a few awesome validations that this gem provide.
|
6
|
+
|
7
|
+
For example, let's say you want your operation `create` to require a `Fixnum` parameter between 1 and 99. With strong_parameters, you're out of luck. With this gem, you simply write in your controller:
|
8
|
+
``` ruby
|
9
|
+
class Api::PeopleController < Api::BaseController
|
10
|
+
def create
|
11
|
+
validated_params = validate_params params do
|
12
|
+
param :age, type: Fixnum, allow: (1..99)
|
13
|
+
end
|
14
|
+
|
15
|
+
# Do something with the validated parameters.
|
16
|
+
end
|
17
|
+
end
|
18
|
+
```
|
19
|
+
|
20
|
+
So when you use this controller:
|
21
|
+
``` ruby
|
22
|
+
> app.post 'api/people', age: 12 # validated_params = { age: 12 }
|
23
|
+
> app.post 'api/people', age: 100 # throws a ParameterSchema::InvalidParameters
|
24
|
+
```
|
25
|
+
|
26
|
+
## Why use this gem instead of strong_parameters
|
27
|
+
|
28
|
+
* You prefer a procedural approach (via a DSL) over a declarative one.
|
29
|
+
* You want more control over the parameters of your API, at the type and format level.
|
30
|
+
* You want to do things differently, you darn hipster ;)
|
31
|
+
|
32
|
+
## Installation
|
33
|
+
|
34
|
+
Add in your Gemfile:
|
35
|
+
``` ruby
|
36
|
+
gem 'parameters_schema'
|
37
|
+
```
|
38
|
+
|
39
|
+
Add in your project:
|
40
|
+
``` ruby
|
41
|
+
require 'parameters_schema'
|
42
|
+
```
|
43
|
+
|
44
|
+
## Schema
|
45
|
+
|
46
|
+
The schema is the heart of this gem. It provides a simple DSL to express an operation's parameters.
|
47
|
+
|
48
|
+
Creating a schema:
|
49
|
+
``` ruby
|
50
|
+
schema = ParametersSchema::Schema.new do
|
51
|
+
# Define parameters here...
|
52
|
+
# ... but an empty schema is also valid.
|
53
|
+
end
|
54
|
+
```
|
55
|
+
Validating parameters against a schema:
|
56
|
+
``` ruby
|
57
|
+
params = { potatoe: 'Eramosa' }
|
58
|
+
schema.validate!(params)
|
59
|
+
```
|
60
|
+
|
61
|
+
The minimal representation of a parameter is:
|
62
|
+
``` ruby
|
63
|
+
param :potatoe
|
64
|
+
```
|
65
|
+
This represents a `required` parameter of type `String` accepting any characters and which doesn't allow nil or empty values.
|
66
|
+
|
67
|
+
The valid options for a parameter are:
|
68
|
+
``` ruby
|
69
|
+
* required # Whether the parameter is required. Default: true.
|
70
|
+
* type # The type of the parameter. Default: String.
|
71
|
+
* allow # The allowed values of the parameter. Default: :any.
|
72
|
+
* deny # The denied values of the parameter. Default: :none.
|
73
|
+
* array # Whether the parameter is an array. Default: false.
|
74
|
+
```
|
75
|
+
|
76
|
+
### Parameter types
|
77
|
+
|
78
|
+
The available types are:
|
79
|
+
``` ruby
|
80
|
+
* String
|
81
|
+
* Symbol
|
82
|
+
* Fixnum
|
83
|
+
* Float
|
84
|
+
* Date
|
85
|
+
* DateTime
|
86
|
+
* Array # An array of :any types.
|
87
|
+
* Hash # An object which members are not validated further.
|
88
|
+
* :boolean # See options for accepted values.
|
89
|
+
* :any # Accepts any value type.
|
90
|
+
```
|
91
|
+
|
92
|
+
To accept more than one type, you can do:
|
93
|
+
``` ruby
|
94
|
+
param :potatoe, type: [Boolean, String] # Accepts a boolean or string value.
|
95
|
+
```
|
96
|
+
|
97
|
+
To accept an array of a specific type, you can do:
|
98
|
+
``` ruby
|
99
|
+
param :potatoes, type: { Array => String } # Accepts an array of strings.
|
100
|
+
```
|
101
|
+
|
102
|
+
To deeper refine the schema of an object, you pass a block to the parameter:
|
103
|
+
``` ruby
|
104
|
+
param :potatoe do # Implicitly of type Hash
|
105
|
+
param :variety
|
106
|
+
param :origin
|
107
|
+
end
|
108
|
+
```
|
109
|
+
|
110
|
+
As you have seen above, a parameter can be of type `Array` but can also have the option `array`. Confusing, right? This option was introduced to simplify the `type` syntax. For example:
|
111
|
+
``` ruby
|
112
|
+
param :potatoes, type: String, array: true # This is equivalent...
|
113
|
+
param :potatoes, type: { Array => String } # ... to this.
|
114
|
+
```
|
115
|
+
|
116
|
+
But this parameter truly shine with an array of objects:
|
117
|
+
``` ruby
|
118
|
+
param :potatoes, array: true do
|
119
|
+
param :variety
|
120
|
+
param :origin
|
121
|
+
end
|
122
|
+
|
123
|
+
# This syntax is also valid but less sexy:
|
124
|
+
param :potatoes, type: { Array => Hash } do
|
125
|
+
param :variety
|
126
|
+
param :origin
|
127
|
+
end
|
128
|
+
```
|
129
|
+
|
130
|
+
#### Gotchas
|
131
|
+
* A `Float` value can be passed to a `Fixnum` parameter but will loose its precision.
|
132
|
+
* Some types accepts more than one representation. Example: `Symbol` accepts any type that respond to `:to_sym`.
|
133
|
+
* If you define multiple types (ex: `[Symbol, String]`), values are interpreted in this order. So the value `'a'` will be cast to `:a`.
|
134
|
+
* Defining the type `{ Fixnum => Date }` doesn't make sense so it falls back to `Fixnum` (the key).
|
135
|
+
* `{ Array => Array }` is accepted. It means a 2D array of `:any`.
|
136
|
+
* `{ Array => Array => ... }` is not yet supported. Did I hear pull request?
|
137
|
+
|
138
|
+
### The `allow` and `deny` options
|
139
|
+
|
140
|
+
By default, the value of a parameter can be any one in the spectrum of a type, with the exception of nil and empty. The `allow` and `deny` options can be used to further refine the accepted values.
|
141
|
+
|
142
|
+
To accept nil or empty values:
|
143
|
+
``` ruby
|
144
|
+
param :potatoe, allow: :nil
|
145
|
+
# => accepts nil, 'Kennebec' but not ''.
|
146
|
+
|
147
|
+
param :potatoe, allow: :empty
|
148
|
+
# => accepts '', 'Kennebec' but not nil.
|
149
|
+
|
150
|
+
param :potatoe, allow: [:nil, :empty]
|
151
|
+
# => accepts nil, '' and 'Kennebec'
|
152
|
+
```
|
153
|
+
Of course, this *nil* or *empty* restriction doesn't make sense for all the types so it will only be applied when it does.
|
154
|
+
|
155
|
+
To accept predefined values:
|
156
|
+
``` ruby
|
157
|
+
param :potatoe, allow: ['Superior', 'Ac Belmont', 'Eramosa'] # this is case-sensitive.
|
158
|
+
|
159
|
+
# Gotcha: this will allow empty values even if you wanted to accept the value 'empty'. You can redefine keywords in the options.
|
160
|
+
param :potatoe, type: Symbol, allow: [:superior, :ac_belmont, :empty]
|
161
|
+
```
|
162
|
+
|
163
|
+
To accept a value matching a regex:
|
164
|
+
``` ruby
|
165
|
+
param :potatoe, allow: /^[a-zA-Z]*$/
|
166
|
+
|
167
|
+
# Gotcha: even though the regex above allows empty values, it must be explicitly stated:
|
168
|
+
param :potatoe, allow: [:empty, /^[a-zA-Z]*$/]
|
169
|
+
```
|
170
|
+
|
171
|
+
To accept a value in a range:
|
172
|
+
``` ruby
|
173
|
+
param :potatoe, type: Fixnum, allow: (1..3)
|
174
|
+
# => accepts 1, 2, 3 but will fail on any other value.
|
175
|
+
```
|
176
|
+
|
177
|
+
The `deny` option is conceptually identical to `allow` but a value will fail the validation if a match is found:
|
178
|
+
``` ruby
|
179
|
+
param :potatoe, type: Fixnum, deny: (1..3)
|
180
|
+
# => accepts any value except 1, 2, 3.
|
181
|
+
```
|
182
|
+
|
183
|
+
The options `allow` and `deny` are validated independently. So beware to not define `allow` and `deny` options that encompass all the possible values of the parameter!
|
184
|
+
|
185
|
+
## Exceptions
|
186
|
+
|
187
|
+
When the validation fails, an instance of `ParametersSchema::InvalidParameters` is raised. This exception contains the attribute `errors` which is an hash of `{ key: error_code }` that you can work with.
|
188
|
+
|
189
|
+
Simple case:
|
190
|
+
``` ruby
|
191
|
+
ParametersSchema::Schema.new do
|
192
|
+
param :potatoe
|
193
|
+
end.validate!({})
|
194
|
+
|
195
|
+
# => ParametersSchema::InvalidParameters
|
196
|
+
# @errors = { potatoe: :missing }
|
197
|
+
```
|
198
|
+
|
199
|
+
The validation process tries to accumulate as many errors as possible before raising the exception, so you can have a precise picture of what went wrong:
|
200
|
+
``` ruby
|
201
|
+
ParametersSchema::Schema.new do
|
202
|
+
param :potatoe do
|
203
|
+
param :name
|
204
|
+
param :type, allow: ['Atlantic']
|
205
|
+
end
|
206
|
+
end.validate!(potatoe: { type: 'Conestoga' })
|
207
|
+
|
208
|
+
# => ParametersSchema::InvalidParameters
|
209
|
+
# @errors = { potatoe: { name: :missing, type: :disallowed } }
|
210
|
+
```
|
211
|
+
|
212
|
+
The possible error codes are (in the order the are validated):
|
213
|
+
``` ruby
|
214
|
+
* :unknown # The parameter is provided but not defined in the schema.
|
215
|
+
* :missing # The parameter is required but is missing.
|
216
|
+
* :nil # The value cannot be nil but is nil.
|
217
|
+
* :empty # The value cannot be empty but is empty.
|
218
|
+
* :disallowed # The value has an invalid format (type/allow) other than nil/empty.
|
219
|
+
```
|
220
|
+
|
221
|
+
## Integrate with Rails
|
222
|
+
|
223
|
+
This gem can be used outside of Rails but was created with Rails in mind. For example, the parameters `controller, action, format` are skipped by default (see Options section to override this behavior) and the parameters are defined in a `Hash`. However, this gem doesn't insinuate itself in your project so you must manually add it in your controllers or anywhere else that make sense to you. Here is a little recipe to add validation in your API pipeline:
|
224
|
+
|
225
|
+
In the base controller of your API, add this **helper**:
|
226
|
+
``` ruby
|
227
|
+
# Validate the parameters of an action, using a schema.
|
228
|
+
# Returns the validated parameters and throw exceptions on invalid input.
|
229
|
+
def validate_params(¶meters_schema)
|
230
|
+
schema = ParametersSchema::Schema.new(¶meters_schema)
|
231
|
+
schema.validate!(params)
|
232
|
+
end
|
233
|
+
```
|
234
|
+
In the base controller of your API, add this **exception handler**:
|
235
|
+
``` ruby
|
236
|
+
# Handle errors related to invalid parameters.
|
237
|
+
rescue_from ParametersSchema::InvalidParameters do |e|
|
238
|
+
# Do something with the exception (ex: log it).
|
239
|
+
|
240
|
+
# Render the response.
|
241
|
+
render json: ..., status: :bad_request
|
242
|
+
end
|
243
|
+
```
|
244
|
+
|
245
|
+
Now in any controller where you want to validate the parameters, you can do:
|
246
|
+
``` ruby
|
247
|
+
def operation
|
248
|
+
validated_params = validate_params do
|
249
|
+
# ...
|
250
|
+
end
|
251
|
+
# ...
|
252
|
+
end
|
253
|
+
```
|
254
|
+
|
255
|
+
## Options
|
256
|
+
|
257
|
+
Options can be specified on the module `ParametersSchema::Options`. Example:
|
258
|
+
|
259
|
+
``` ruby
|
260
|
+
ParametersSchema::Options.skip_parameters = [:internal_stuff]
|
261
|
+
```
|
262
|
+
|
263
|
+
Available options:
|
264
|
+
* `skip_parameters` an array of first-level parameters to skip. Default: `[:controller, :action, :format]`.
|
265
|
+
* `empty_keyword` the keyword used to represent an empty value. Default: `:empty`.
|
266
|
+
* `any_keyword` the keyword used to represent any value. Default: `:any`.
|
267
|
+
* `none_keyword` the keyword used to represent no value. Default: `:none`.
|
268
|
+
* `boolean_keyword` the keyword used to represent a boolean value. Default: `:boolean`.
|
269
|
+
* `nil_keyword` the keyword used to represent a nil value. Default: `:nil`.
|
270
|
+
* `boolean_true_values` the accepted boolean true values. Not case-sensitive. Default: `true`, `'t'`, `'true'`, `'1'`, `1`, `1.0`.
|
271
|
+
* `boolean_false_values` the accepted boolean false values. Not case-sensitive. Default: `false`, `'f'`, `'false'`, `'0'`, `0`, `0.0`.
|
272
|
+
|
273
|
+
## Contribute
|
274
|
+
|
275
|
+
Yes, please. Bug fixes, new features, refactoring, unit tests. Send your precious pull requests.
|
276
|
+
|
277
|
+
### Ideas
|
278
|
+
|
279
|
+
* Array of arrays of ...
|
280
|
+
* Min/Max for numeric values
|
281
|
+
* More `allow` options
|
282
|
+
* Better refine error codes
|
283
|
+
|
284
|
+
## License
|
285
|
+
|
286
|
+
Parameters Schema is released under the [MIT License](http://www.opensource.org/licenses/MIT).
|
data/Rakefile
CHANGED
@@ -1,8 +1,8 @@
|
|
1
|
-
require 'rake/testtask'
|
2
|
-
|
3
|
-
Rake::TestTask.new do |t|
|
4
|
-
t.libs << 'test'
|
5
|
-
end
|
6
|
-
|
7
|
-
desc 'Run tests'
|
1
|
+
require 'rake/testtask'
|
2
|
+
|
3
|
+
Rake::TestTask.new do |t|
|
4
|
+
t.libs << 'test'
|
5
|
+
end
|
6
|
+
|
7
|
+
desc 'Run tests'
|
8
8
|
task default: :test
|
@@ -1,21 +1,21 @@
|
|
1
|
-
class Object
|
2
|
-
#
|
3
|
-
# Check if object is numeric.
|
4
|
-
# From http://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails
|
5
|
-
#
|
6
|
-
# p "1".numeric? # => true
|
7
|
-
# p "1.2".numeric? # => true
|
8
|
-
# p "5.4e-29".numeric? # => true
|
9
|
-
# p "12e20".numeric? # => true
|
10
|
-
# p "1a".numeric? # => false
|
11
|
-
# p "1.2.3.4".numeric? # => false
|
12
|
-
#
|
13
|
-
def numeric?
|
14
|
-
return true if self.kind_of?(Numeric)
|
15
|
-
return true if self.to_s =~ /^\d+$/
|
16
|
-
Float(self)
|
17
|
-
true
|
18
|
-
rescue
|
19
|
-
false
|
20
|
-
end
|
21
|
-
end
|
1
|
+
class Object
|
2
|
+
#
|
3
|
+
# Check if object is numeric.
|
4
|
+
# From http://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails
|
5
|
+
#
|
6
|
+
# p "1".numeric? # => true
|
7
|
+
# p "1.2".numeric? # => true
|
8
|
+
# p "5.4e-29".numeric? # => true
|
9
|
+
# p "12e20".numeric? # => true
|
10
|
+
# p "1a".numeric? # => false
|
11
|
+
# p "1.2.3.4".numeric? # => false
|
12
|
+
#
|
13
|
+
def numeric?
|
14
|
+
return true if self.kind_of?(Numeric)
|
15
|
+
return true if self.to_s =~ /^\d+$/
|
16
|
+
Float(self)
|
17
|
+
true
|
18
|
+
rescue
|
19
|
+
false
|
20
|
+
end
|
21
|
+
end
|