rschema 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 662ddf40b94f44cf6f4bc714fe44346621974aa8
4
+ data.tar.gz: 03728273b1dec3e5cf5ed7be62bd5e59a6d1a299
5
+ SHA512:
6
+ metadata.gz: dec3b9214d875a3f0f1673fd4f230e007c3f330750d10fd436c51a912385212edd909eb102e125722090350ff8cc1bba695e28bd6bb040e8cbae8fa2f71c77e3
7
+ data.tar.gz: 5d422ebd5d992205ce437b20233a8575b5cc0f2e8a69d0ab23f74b55ca7292316c1ddfb0ba709f8d1b6a43e259067c9dd045f3c1d2b1106baf9001dccd221724
data/LICENSE.txt ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
data/README.md ADDED
@@ -0,0 +1,267 @@
1
+ # RSchema
2
+
3
+ Schema-based validation and coercion for Ruby data structures. Heavily inspired
4
+ by (read: stolen from) [Prismatic/schema][] for Clojure.
5
+
6
+ Meet RSchema
7
+ ------------
8
+
9
+ A "schema" is a data structure that describes the _shape_ of data.
10
+ Schemas are generally just plain old hashes, arrays, and classes.
11
+
12
+ ```ruby
13
+ post_schema = {
14
+ title: String,
15
+ tags: [Symbol],
16
+ body: String
17
+ }
18
+ ```
19
+
20
+ Schemas can be used to validate data. That is, they can check whether
21
+ data is in the correct shape:
22
+
23
+ ```ruby
24
+ RSchema.validate!(post_schema, {
25
+ title: "You won't beleive how this developer foo'd her bar",
26
+ tags: [:foos, :bars, :unbeleivable],
27
+ body: '<p>blah blah</p>'
28
+ }) # ok
29
+ ```
30
+
31
+ What is a schema?
32
+ -----------------
33
+
34
+ Schemas are Ruby data structures. The simplest type of schema is just a class:
35
+
36
+ ```ruby
37
+ schema = Integer
38
+ RSchema.validate!(schema, 5) # ok
39
+ RSchema.validate!(schema, 'hello') # !!! raises RSchema::ValidationError !!!
40
+ ```
41
+
42
+ Then there are composite schemas, which are schemas composed of subschemas.
43
+ Arrays are composite schemas:
44
+
45
+ ```ruby
46
+ schema = [Integer]
47
+ RSchema.validate!(schema, [10, 11, 12]) # ok
48
+ RSchema.validate!(schema, [10, 11, '12']) # !!! raises RSchema::ValidationError !!!
49
+ ```
50
+
51
+ And so are hashes:
52
+
53
+ ```ruby
54
+ schema = { fname: String, age: Integer }
55
+ RSchema.validate!(schema, { fname: 'Jane', age: 27 }) # ok
56
+ RSchema.validate!(schema, { fname: 'Johnny' }) # !!! raises RSchema::ValidationError !!!
57
+ ```
58
+
59
+ While schemas are just plain old Ruby data structures, RSchema also provides
60
+ an extensible DSL for constructing more complicated schemas:
61
+
62
+ ```ruby
63
+ schema = RSchema.schema {{
64
+ fname: predicate { |n| n.is_a?(String) && n.size > 0 },
65
+ favourite_foods: set_of(Symbol),
66
+ children_by_age: hash_of(Integer => String)
67
+ }}
68
+
69
+ RSchema.validate!(schema, {
70
+ fname: 'Johnny',
71
+ favourite_foods: Set.new([:bacon, :cheese, :onion]),
72
+ children_by_age: {
73
+ 7 => 'Jenny',
74
+ 5 => 'Simon'
75
+ }
76
+ }) # ok
77
+ ```
78
+
79
+ Array Schemas
80
+ -------------
81
+
82
+ There are two types of array schemas. When the array schema has a single
83
+ element, it is a variable-length array schema:
84
+
85
+ ```ruby
86
+ schema = [Symbol]
87
+ RSchema.validate!(schema, [:a, :b, :c]) # ok
88
+ RSchema.validate!(schema, [:a]) # ok
89
+ RSchema.validate!(schema, []) # ok
90
+ ```
91
+
92
+ Otherwise, it is a fixed-length array schema
93
+
94
+ ```ruby
95
+ schema = [Integer, String]
96
+ RSchema.validate!(schema, [10, 'hello']) # ok
97
+ RSchema.validate!(schema, [10, 'hello', 'world']) # !!! raises RSchema::ValidationError !!!
98
+ RSchema.validate!(schema, [10]) # !!! raises RSchema::ValidationError !!!
99
+ ```
100
+
101
+ Hash Schemas
102
+ ------------
103
+
104
+ Hash schemas map constant keys to subschema values:
105
+
106
+ ```ruby
107
+ schema = { fname: String }
108
+ RSchema.validate!(schema, { fname: 'William' }) # ok
109
+ ```
110
+
111
+ Keys can be optional:
112
+
113
+ ```ruby
114
+ schema = RSchema.schema {{
115
+ :fname => String,
116
+ _?(:age) => Integer
117
+ }}
118
+ RSchema.validate!(schema, { fname: 'Lucy', age: 21 }) # ok
119
+ RSchema.validate!(schema, { fname: 'Tom' }) # ok
120
+ ```
121
+
122
+ There is also another type of hash schema that represents hashes with variable
123
+ keys:
124
+
125
+ ```ruby
126
+ schema = RSchema.schema { hash_of(String => Integer) }
127
+ RSchema.validate!(schema, { 'hello' => 1, 'world' => 2 }) # ok
128
+ RSchema.validate!(schema, { 'hello' => 1 }) # ok
129
+ RSchema.validate!(schema, {}) # ok
130
+ ```
131
+
132
+ Other Schema Types
133
+ ------------------
134
+
135
+ RSchema provides a few other schema types through its DSL:
136
+
137
+ ```ruby
138
+ # predicate
139
+ predicate_schema = RSchema.schema do
140
+ predicate('even') { |x| x.even? }
141
+ end
142
+ RSchema.validate!(predicate_schema, 4) # ok
143
+ RSchema.validate!(predicate_schema, 5) # !!! raises RSchema::ValidationError !!!
144
+
145
+ # maybe
146
+ maybe_schema = RSchema.schema do
147
+ maybe(Integer)
148
+ end
149
+ RSchema.validate!(maybe_schema, 5) # ok
150
+ RSchema.validate!(maybe_schema, nil) # ok
151
+
152
+ # enum
153
+ enum_schema = RSchema.schema do
154
+ enum([:a, :b, :c])
155
+ end
156
+ RSchema.validate!(enum_schema, :a) # ok
157
+ RSchema.validate!(enum_schema, :z) # !!! raises RSchema::ValidationError !!!
158
+ ```
159
+
160
+ Coercion
161
+ --------
162
+
163
+ RSchema is capable of coercing invalid values into valid ones, in some
164
+ situations. Here are some examples:
165
+
166
+ ```ruby
167
+ RSchema.coerce!(Symbol, "hello") #=> :hello
168
+ RSchema.coerce!(String, :hello) #=> "hello"
169
+ RSchema.coerce!(Integer, "5") #=> 5
170
+ RSchema.coerce!(Integer, "cat") # !!! raises RSchema::ValidationError !!!
171
+ RSchema.coerce!(Set, [1, 2, 3]) #=> <Set: {1, 2, 3}>
172
+
173
+ schema = RSchema.schema {{
174
+ fname: String,
175
+ favourite_foods: set_of(Symbol)
176
+ }}
177
+
178
+ value = {
179
+ fname: 'Peggy',
180
+ favourite_foods: ['berries', 'cake']
181
+ }
182
+
183
+ RSchema.coerce!(schema, value)
184
+ #=> { fname: "Peggy", favourite_foods: <Set: #{:berries, :cake}> }
185
+ ```
186
+
187
+ Extending the DSL
188
+ -----------------
189
+
190
+ The RSchema DSL can be extended by adding methods to the `RSchema::DSL` module:
191
+
192
+ ```ruby
193
+ module RSchema::DSL
194
+ def self.positive_and_even(type)
195
+ predicate { |x| x > 0 && x.even? }
196
+ end
197
+ end
198
+
199
+ schema = RSchema.schema { positive_and_even }
200
+ RSchema.validate!(schema, 6) # ok
201
+ RSchema.validate!(schema, -6) # !!! raises RSchema::ValidationError !!!
202
+ ```
203
+
204
+ Custom Schema Types
205
+ -------------------
206
+
207
+ Any Ruby object can be a schema, as long as it implements the `schema_walk`
208
+ method. Here is a schema called `Coordinate`, which is an x/y pair of `Float`s
209
+ in an array:
210
+
211
+ ```ruby
212
+ # make the schema type class
213
+ class CoordinateSchema
214
+ def schema_walk(value, mapper)
215
+ # validate `value`
216
+ return RSchema::ErrorDetails.new('is not an Array') unless value.is_a?(Array)
217
+ return RSchema::ErrorDetails.new('does not have two elements') unless value.size == 2
218
+
219
+ # walk the subschemas/subvalues
220
+ x, x_error = RSchema.walk(Float, value[0], mapper)
221
+ y, y_error = RSchema.walk(Float, value[1], mapper)
222
+
223
+ # look for subschema errors, and propagate them if found
224
+ return RSchema::ErrorDetails.new({ x: x_error.details }) if x_error
225
+ return RSchema::ErrorDetails.new({ y: y_error.details }) if y_error
226
+
227
+ # return the valid value
228
+ [x, y]
229
+ end
230
+ end
231
+
232
+ # add some DSL
233
+ module RSchema::DSL
234
+ def self.coordinate
235
+ CoordinateSchema.new
236
+ end
237
+ end
238
+
239
+ # use the custom schema type (coercion works too)
240
+ schema = RSchema.schema { coordinate }
241
+ RSchema.validate!(schema, [1.0, 2.0]) # ok
242
+ RSchema.validate!(schema, [1, 2]) # !!! raises RSchema::ValidationError !!!
243
+ RSchema.coerce!(schema, ["1", "2"]) #=> [1.0, 2.0]
244
+ ```
245
+
246
+ The `schema_walk` method receives two arguments:
247
+
248
+ - `value`: the value that is being validated against this schema
249
+ - `mapper`: not usually used by the schema, but must be passed to
250
+ `RSchema.walk`.
251
+
252
+ The `schema_walk` method has three responsibilities:
253
+
254
+ 1. It must validate the given value. If the value is invalid, the method must
255
+ return an `RSchema::ErrorDetails` object. If the value is valid, it must
256
+ return the valid value after walking all subvalues.
257
+
258
+ 2. For composite schemas, it must walk subvalues by calling `RSchema.walk`.
259
+ The example above walks two subvalues (`value[0]` and `value[1]`) with the
260
+ `Float` schema.
261
+
262
+ 3. It must propagate any `RSchema::ErrorDetails` objects returned from walking
263
+ the subvalues. Walking subvalues with `RSchema.walk` may return an error,
264
+ in which case the `rschema_walk` method must also return an error.
265
+
266
+ [Prismatic/schema]: https://github.com/Prismatic/schema
267
+
data/lib/rschema.rb ADDED
@@ -0,0 +1,278 @@
1
+ require 'set'
2
+
3
+ module RSchema
4
+ InvalidSchemaError = Class.new(StandardError)
5
+ ValidationError = Class.new(StandardError)
6
+ OptionalHashKey = Struct.new(:key)
7
+ ErrorDetails = Struct.new(:details) do
8
+ def to_s; inspect; end
9
+ def inspect; details.inspect; end
10
+ end
11
+
12
+ def self.schema(&block)
13
+ DSL.instance_exec(&block)
14
+ end
15
+
16
+ def self.validation_errors(schema, value)
17
+ _, error = walk(schema, value)
18
+ error
19
+ end
20
+
21
+ def self.validate!(schema, value)
22
+ result, error = walk(schema, value)
23
+ if error.nil?
24
+ result
25
+ else
26
+ raise(ValidationError, error)
27
+ end
28
+ end
29
+
30
+ def self.coerce(schema, value)
31
+ walk(schema, value, CoercionMapper)
32
+ end
33
+
34
+ def self.coerce!(schema, value)
35
+ result, error = walk(schema, value, CoercionMapper)
36
+ if error.nil?
37
+ result
38
+ else
39
+ raise(ValidationError, error)
40
+ end
41
+ end
42
+
43
+ def self.walk(schema, value, mapper = nil)
44
+ raise(InvalidSchemaError, schema) unless schema.respond_to?(:schema_walk)
45
+ value = mapper.prewalk(schema, value) if mapper
46
+ value = schema.schema_walk(value, mapper)
47
+ value = mapper.postwalk(schema, value) if mapper
48
+
49
+ if value.is_a?(RSchema::ErrorDetails)
50
+ [nil, value]
51
+ else
52
+ [value, nil]
53
+ end
54
+ end
55
+
56
+ module DSL
57
+ def self._?(key)
58
+ OptionalHashKey.new(key)
59
+ end
60
+
61
+ def self.hash_of(subschemas_hash)
62
+ raise InvalidSchemaError unless subschemas_hash.size == 1
63
+ GenericHashSchema.new(subschemas_hash.keys.first, subschemas_hash.values.first)
64
+ end
65
+
66
+ def self.set_of(subschema)
67
+ GenericSetSchema.new(subschema)
68
+ end
69
+
70
+ def self.predicate(name = nil, &block)
71
+ raise InvalidSchemaError unless block
72
+ PredicateSchema.new(name, block)
73
+ end
74
+
75
+ def self.maybe(subschema)
76
+ raise InvalidSchemaError unless subschema
77
+ MaybeSchema.new(subschema)
78
+ end
79
+
80
+ def self.enum(possible_values, subschema = nil)
81
+ raise InvalidSchemaError unless possible_values && possible_values.size > 0
82
+ EnumSchema.new(Set.new(possible_values), subschema)
83
+ end
84
+ end
85
+
86
+ module CoercionMapper
87
+ def self.prewalk(schema, value)
88
+ if schema == Integer && value.is_a?(String)
89
+ try_convert(value) { Integer(value) }
90
+ elsif schema == Float && value.is_a?(String)
91
+ try_convert(value) { Float(value) }
92
+ elsif schema == Float && value.is_a?(Integer)
93
+ value.to_f
94
+ elsif schema == Symbol && value.is_a?(String)
95
+ value.to_sym
96
+ elsif schema == String && value.is_a?(Symbol)
97
+ value.to_s
98
+ elsif schema == Array && value.is_a?(Set)
99
+ value.to_a
100
+ elsif (schema == Set || schema.is_a?(GenericSetSchema)) && value.is_a?(Array)
101
+ Set.new(value)
102
+ elsif(schema.is_a?(Hash) && value.is_a?(Hash))
103
+ coerce_hash(schema, value)
104
+ else
105
+ value
106
+ end
107
+ end
108
+
109
+ def self.postwalk(schema, value)
110
+ value
111
+ end
112
+
113
+ def self.try_convert(x)
114
+ yield x
115
+ rescue
116
+ x
117
+ end
118
+
119
+ def self.coerce_hash(schema, value)
120
+ symbol_keys = Set.new(schema.keys.select{ |k| k.is_a?(Symbol) }.map(&:to_s))
121
+ value.reduce({}) do |accum, (k, v)|
122
+ # convert string keys to symbol keys, if needed
123
+ if k.is_a?(String) && symbol_keys.include?(k)
124
+ k = k.to_sym
125
+ end
126
+
127
+ # strip out keys that don't exist in the schema
128
+ if schema.has_key?(k)
129
+ accum[k] = v
130
+ end
131
+
132
+ accum
133
+ end
134
+ end
135
+ end
136
+
137
+ GenericHashSchema = Struct.new(:key_subschema, :value_subschema) do
138
+ def schema_walk(value, mapper)
139
+ if not value.is_a?(Hash)
140
+ return RSchema::ErrorDetails.new('is not a Hash')
141
+ end
142
+
143
+ value.reduce({}) do |accum, (k, v)|
144
+ # walk key
145
+ k_walked, error = RSchema.walk(key_subschema, k, mapper)
146
+ break RSchema::ErrorDetails.new({'has invalid key, where' => error.details}) if error
147
+
148
+ # walk value
149
+ v_walked, error = RSchema.walk(value_subschema, v, mapper)
150
+ break RSchema::ErrorDetails.new({k => error.details}) if error
151
+
152
+ accum[k_walked] = v_walked
153
+ accum
154
+ end
155
+ end
156
+ end
157
+
158
+ GenericSetSchema = Struct.new(:subschema) do
159
+ def schema_walk(value, mapper)
160
+ return RSchema::ErrorDetails.new('is not a Set') if not value.is_a?(Set)
161
+
162
+ value.reduce(Set.new) do |accum, subvalue|
163
+ subvalue_walked, error = RSchema.walk(subschema, subvalue, mapper)
164
+ break RSchema::ErrorDetails.new(Set.new([error.details])) if error
165
+
166
+ accum << subvalue_walked
167
+ accum
168
+ end
169
+ end
170
+ end
171
+
172
+ PredicateSchema = Struct.new(:name, :block) do
173
+ def schema_walk(value, mapper)
174
+ if block.call(value)
175
+ value
176
+ else
177
+ RSchema::ErrorDetails.new('fails predicate' + (name ? ": #{name}" : ''))
178
+ end
179
+ end
180
+ end
181
+
182
+ MaybeSchema = Struct.new(:subschema) do
183
+ def schema_walk(value, mapper)
184
+ if value.nil?
185
+ value
186
+ else
187
+ subvalue_walked, error = RSchema.walk(subschema, value, mapper)
188
+ error || subvalue_walked
189
+ end
190
+ end
191
+ end
192
+
193
+ EnumSchema = Struct.new(:value_set, :subschema) do
194
+ def schema_walk(value, mapper)
195
+ value_walked = if subschema
196
+ v, error = RSchema.walk(subschema, value, mapper)
197
+ return error if error
198
+ v
199
+ else
200
+ value
201
+ end
202
+
203
+ if value_set.include?(value_walked)
204
+ value_walked
205
+ else
206
+ RSchema::ErrorDetails.new("#{value_walked} is not a valid enum member")
207
+ end
208
+ end
209
+ end
210
+ end
211
+
212
+ class Class
213
+ def schema_walk(value, mapper)
214
+ if value.is_a?(self)
215
+ value
216
+ else
217
+ RSchema::ErrorDetails.new("is not a #{self}")
218
+ end
219
+ end
220
+ end
221
+
222
+ class Array
223
+ def schema_walk(value, mapper)
224
+ fixed_size = (size != 1)
225
+
226
+ if not value.is_a?(Array)
227
+ RSchema::ErrorDetails.new("is not an Array")
228
+ elsif fixed_size && value.size != size
229
+ RSchema::ErrorDetails.new("does not have #{size} elements")
230
+ else
231
+ value.each.with_index.map do |subvalue, idx|
232
+ subschema = (fixed_size ? self[idx] : first)
233
+ subvalue_walked, error = RSchema.walk(subschema, subvalue, mapper)
234
+ break RSchema::ErrorDetails.new({ idx => error.details }) if error
235
+ subvalue_walked
236
+ end
237
+ end
238
+ end
239
+ end
240
+
241
+ class Hash
242
+ def schema_walk(value, mapper)
243
+ return RSchema::ErrorDetails.new('is not a Hash') if not value.is_a?(Hash)
244
+
245
+ # extract details from the schema
246
+ required_keys = Set.new
247
+ all_subschemas = {}
248
+ each do |(k, subschema)|
249
+ if k.is_a?(RSchema::OptionalHashKey)
250
+ all_subschemas[k.key] = subschema
251
+ else
252
+ required_keys << k
253
+ all_subschemas[k] = subschema
254
+ end
255
+ end
256
+
257
+ # check for extra keys that shouldn't be there
258
+ extraneous = value.keys.reject{ |k| all_subschemas.has_key?(k) }
259
+ if extraneous.size > 0
260
+ return RSchema::ErrorDetails.new({"has extraneous keys" => extraneous})
261
+ end
262
+
263
+ # check for required keys that are missing
264
+ missing_requireds = required_keys.reject{ |k| value.has_key?(k) }
265
+ if missing_requireds.size > 0
266
+ return RSchema::ErrorDetails.new({"is missing required keys" => missing_requireds})
267
+ end
268
+
269
+ # walk the subvalues
270
+ value.reduce({}) do |accum, (k, subvalue)|
271
+ subvalue_walked, error = RSchema.walk(all_subschemas[k], subvalue, mapper)
272
+ break RSchema::ErrorDetails.new({ k => error.details }) if error
273
+ accum[k] = subvalue_walked
274
+ accum
275
+ end
276
+ end
277
+ end
278
+
@@ -0,0 +1,19 @@
1
+ module RSchema
2
+ module RailsInterop
3
+ ParamSchemaValidationError = Class.new(StandardError)
4
+
5
+ module ControllerMethods
6
+ def params_for_schema!(schema_arg = nil, &block)
7
+ schema = schema_arg || RSchema.schema(&block)
8
+ value = self.params
9
+ coerced, error = RSchema.coerce(schema, value)
10
+ if error
11
+ raise ParamSchemaValidationError.new(schema: schema, params: value, error: e)
12
+ else
13
+ coerced
14
+ end
15
+ end
16
+ end
17
+
18
+ end
19
+ end
@@ -0,0 +1,3 @@
1
+ module RSchema
2
+ VERSION = '0.1.0'
3
+ end
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rschema
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Tom Dalling
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-01-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description: |2
42
+ Schema-based validation and coercion for Ruby data structures. Heavily inspired
43
+ by (read: stolen from) [Prismatic/schema][] for Clojure.
44
+ email:
45
+ - tom@tomdalling.com
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - LICENSE.txt
51
+ - README.md
52
+ - lib/rschema.rb
53
+ - lib/rschema/rails_interop.rb
54
+ - lib/rschema/version.rb
55
+ homepage: http://www.tomdalling.com/rschema
56
+ licenses:
57
+ - MIT
58
+ metadata: {}
59
+ post_install_message:
60
+ rdoc_options: []
61
+ require_paths:
62
+ - lib
63
+ required_ruby_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubyforge_project:
75
+ rubygems_version: 2.4.4
76
+ signing_key:
77
+ specification_version: 4
78
+ summary: Schema-based validation and coercion for Ruby data structures
79
+ test_files: []