kharon 0.3.1 → 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format documentation
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source "https://rubygems.org/"
2
+ ruby "1.9.3"
3
+
4
+ gem "bson", "2.2.2"
5
+
6
+ # These gems are only used for testing purposes, and shouldn't be used in another environment than the local development one.
7
+ group :test do
8
+ gem "rack-test", "0.6.2"
9
+ gem "rspec" , "3.0.0.beta2"
10
+ end
@@ -0,0 +1,28 @@
1
+ GEM
2
+ remote: https://rubygems.org/
3
+ specs:
4
+ bson (2.2.2)
5
+ diff-lcs (1.2.5)
6
+ rack (1.5.2)
7
+ rack-test (0.6.2)
8
+ rack (>= 1.0)
9
+ rspec (3.0.0.beta2)
10
+ rspec-core (= 3.0.0.beta2)
11
+ rspec-expectations (= 3.0.0.beta2)
12
+ rspec-mocks (= 3.0.0.beta2)
13
+ rspec-core (3.0.0.beta2)
14
+ rspec-support (= 3.0.0.beta2)
15
+ rspec-expectations (3.0.0.beta2)
16
+ diff-lcs (>= 1.2.0, < 2.0)
17
+ rspec-support (= 3.0.0.beta2)
18
+ rspec-mocks (3.0.0.beta2)
19
+ rspec-support (= 3.0.0.beta2)
20
+ rspec-support (3.0.0.beta2)
21
+
22
+ PLATFORMS
23
+ ruby
24
+
25
+ DEPENDENCIES
26
+ bson (= 2.2.2)
27
+ rack-test (= 0.6.2)
28
+ rspec (= 3.0.0.beta2)
data/LICENSE ADDED
@@ -0,0 +1,201 @@
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.
@@ -0,0 +1,206 @@
1
+ # Kharon the boatkeeper
2
+
3
+ ## What is kharon ?
4
+
5
+ Charon (or Khàrôn in ancient greek) was, in the greek mythology, the ferryman to cross the Styx river. He decided who passed, and who didn't pass, and it's exactly what this gem does.
6
+
7
+ It validates the datas in a hash given criterias about its keys, and let the execution of the program continue if the requirements are fulfilled, stop it if not. The datas in the hash are supposed to be strings, Kharon being designed to validate datas coming in a web application from the outside (tipically, datas passed in a querystring or a POST body).
8
+
9
+ ## Contact me
10
+
11
+ For any question or advice, contact me at vincent.courtois@mycar-innovations.com. I'll answer as soon as possible, and thank you by advance for giving me some of your time.
12
+
13
+ ## Requirements
14
+
15
+ You'll just need Ruby 1.9.3 at least to make it work.
16
+
17
+ ## Installation
18
+
19
+ ### From Rubygems.org
20
+
21
+ It's a gem, you know how to install a gem, or you should if you're using it in a ruby application. Okay, let's consider you don't, just type :
22
+
23
+ ```
24
+ gem install kharon
25
+ ```
26
+
27
+ And... That's it ! Now it's installed and you can learn how to properly use it !
28
+
29
+ ### From sources
30
+
31
+ Clone this repository whenether you want, go inside, then type the following command :
32
+
33
+ ```
34
+ gem install kharon-0.3.0
35
+ ```
36
+
37
+ The gem will be installed on your system, from then on you can use it inside your applications.
38
+
39
+ ## Configuration
40
+
41
+ The configuration of the module is simple, juste use the #configure method from the Kharon::Factory module as follow :
42
+
43
+ ```ruby
44
+ Kharon::Factory.configure do |configuration|
45
+ # Decides whether you want to use exceptions or not. Default is TRUE.
46
+ configuration.use_exceptions(true)
47
+ end
48
+ ```
49
+
50
+ ## Run tests
51
+
52
+ This gem is tested using RSpec, to run the tests, clone the repository, go in, then type :
53
+
54
+ ```
55
+ % bundle install
56
+ % bundle exec rspec --format documentation --color
57
+ ```
58
+
59
+ ## How to use the gem
60
+
61
+ First, you need to include the gem to your application. Usually you can just do :
62
+
63
+ ```ruby
64
+ require "kharon"
65
+ ```
66
+
67
+ ### The validator
68
+
69
+ The Kharon::Validator class is the main class of this gem, it offers an interface to validate hashes and see if they fulfill requirements. first, you have to create an instance of the validator :
70
+
71
+ ```ruby
72
+ validator = Kharon::Factory.validator(hash_to_validate)
73
+ ```
74
+
75
+ Now your validator knows which hash it has to validate, now you can do :
76
+
77
+ ```ruby
78
+ # Sees if the "required_integer_key" key is present, and an integer
79
+ validator.integer("required_integer_key", required: true)
80
+ ```
81
+
82
+ All the functions are listed in the full documentation below.
83
+
84
+ ### The helper
85
+
86
+ This gem was firstly designed to be used as a helper for Sinatra applications, so it contains another useful module : Kharon::Helpers. To use it in your Sinatra application, just type this in the controllers where you want it included :
87
+
88
+ ```ruby
89
+ helpers Kharon::Helpers
90
+ ```
91
+
92
+ From there, you can type it in any of the routes of this controller :
93
+
94
+ ```ruby
95
+ validate(hash_to_validate) do
96
+ integer "required_integer_key", required: true
97
+ end
98
+ ```
99
+
100
+ This code is strictly equivalent to the one presented above, it uses the block syntax of ruby to give you a nice and fancy way to validate your datas !
101
+
102
+ ## Full documentation
103
+
104
+ ### Methods
105
+
106
+ Methods signification are pretty straight-forward as it validates type :
107
+ - :integer
108
+ - :numeric
109
+ - :text
110
+ - :any
111
+ - :datetime
112
+ - :date
113
+ - :array
114
+ - :hash
115
+ - :boolean
116
+ - :mongoid
117
+
118
+ #### :any
119
+
120
+ This method will validate any value associated to the given key, it's useful if you just want to pass options like :required or :dependency
121
+
122
+ #### :mongoid
123
+
124
+ This method is only useful if you use Mongoid or an ORM linking MongoDB to your application. It validates the data associated with the key only if it's a string formatted as a MongoDB unique identifier.
125
+
126
+ ### Options
127
+
128
+ #### :required
129
+
130
+ This option can be given to say that a key has to be in the hash for it to be validated. It can be used with all methods.
131
+
132
+ #### :dependency
133
+
134
+ This options say that this key needs another key to be present for the hash to be validated. It can be used with all methods.
135
+
136
+ #### :dependencies
137
+
138
+ This options is used to pass several dependecies at once, as an array of keys. See :dependency option for details. It can be used with all methods.
139
+ Note: the :dependencies option *overrides* the :dependency option if both are given.
140
+
141
+ #### :in
142
+
143
+ This option is used to give an array of possible values for the given key. If the value of the key is not in thius array, the validator fails. It can be used with all methods.
144
+
145
+ #### :equals
146
+
147
+ For the value of a given key in the hash to be equal to the given value. It can be used with all methods.
148
+
149
+ #### :min
150
+
151
+ This option allows you to specify a non-strict minimum limit for the value associated with the given key. The value has to be passed as an integer. It can be used with :numeric or :integer methods.
152
+
153
+ #### :max
154
+
155
+ This option allows you to specify a non-strict maximum limit for the value associated with the given key. The value has to be passed as an integer. It can be used with :numeric or :integer methods.
156
+
157
+ #### :between
158
+
159
+ This option gives an interval in which the value of the given key must be to fulfill the requirement. The value has to be passed as an array of two integers, first the minimum, then the maximum. It can be used with :numeric or :integer methods.
160
+ Note: the :between option *overrides* the :min *and* :max options if several are given.
161
+
162
+ #### :contains
163
+
164
+ This option is used to see if an array or a hash situated at the given key contains some values. The values must be passed as an array. This option can be used with the :hash and :array methods.
165
+
166
+ #### :has_keys
167
+
168
+ This option is used to see if a hash situated at the given key contains some keys. The values must be passed as an array. This option can be used with the :hash and :array methods.
169
+
170
+ #### :cast
171
+
172
+ This option, if not given, is set to TRUE. If given at false, doesn't type cast the result of the validation so you keep the original string and just check its type. It can be used with all methods.
173
+
174
+ #### :extract
175
+
176
+ This option, if not given, is set to TRUE. If given at false, doesn't extract the given key, just validate its type. It can be used with all methods.
177
+
178
+ #### :floor
179
+
180
+ The value of round must be a boolean to work properly. If given at TRUE, floor the decimal number identified by this key. This option can be used with the :numeric method.
181
+
182
+ #### :ceil
183
+
184
+ The value of round must be a boolean to work properly. If given at TRUE, ceil the decimal number identified by this key. This option can be used with the :numeric method.
185
+
186
+ #### :round
187
+
188
+ The value of round must be an integer to work properly. If given, round the decimal number keeping the given number of digits after the comma. This option can be used with the :numeric method.
189
+
190
+ #### :regex
191
+
192
+ The value of this option must be passed as a string. If given as a string, verity that the associated string matches the given regular expression. This option can be used with the :text method.
193
+
194
+ ### Example god damn it !
195
+
196
+ Here is an example to demonstrate the power of Kharon (made with the helper) :
197
+
198
+ ```ruby
199
+ @validated = validate(parameters) do
200
+ numeric "price", required: true, min: 0
201
+ datetime "added"
202
+ text "added_by", dependency: "added"
203
+ end
204
+ ```
205
+
206
+ This example could validate the datas coming in the application in a search engine route for products in a supermarket.
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,21 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'kharon/version'
5
+
6
+ Gem::Specification.new do |specification|
7
+ specification.name = "kharon"
8
+ specification.version = Kharon::VERSION
9
+ specification.date = "2014-04-02"
10
+ specification.summary = "Ruby Hash validator"
11
+ specification.description = "Kharon is a ruby hash validator that helps you fix the structure of a hash (type of the keys, dependencies, ...)."
12
+ specification.authors = ["Vincent Courtois"]
13
+ specification.email = "vincent.courtois@mycar-innovations.com"
14
+ specification.files = `git ls-files`.split($/)
15
+ specification.homepage = "https://rubygems.org/gems/kharon"
16
+ specification.license = "Apache License 2"
17
+ specification.test_files = ["spec/spec_helper.rb", "spec/lib/kharon/validator_spec.rb"]
18
+
19
+ specification.required_ruby_version = ">= 1.9.3"
20
+ specification.add_runtime_dependency "bson", ">= 2.2.2"
21
+ end
@@ -0,0 +1,7 @@
1
+ require "kharon/version"
2
+ require "kharon/validator"
3
+ require "kharon/helpers/validate"
4
+
5
+ module Kharon
6
+
7
+ end
@@ -1,4 +1,5 @@
1
1
  module Kharon
2
+
2
3
  # The validator is the main class of Kharon, it validates a hash given a structure.
3
4
  # @author Vincent Courtois <vincent.courtois@mycar-innovations.com>
4
5
  class Validator
@@ -120,6 +121,26 @@ module Kharon
120
121
  match?(key, /^[0-9a-fA-F]{24}$/) ? store(key, ->(item){BSON::ObjectId.from_string(item.to_s)}, options) : raise_type_error(key, "Moped::BSON::ObjectId")
121
122
  end
122
123
 
124
+ # Checks if the given key is a box (geofences) or not. A box is composed of four numbers (positive or negative, decimal or not) separed by commas.
125
+ # @param [Object] key the key about which verify the type.
126
+ # @param [Hash] options a hash of options passed to this method (see documentation to know which options pass).
127
+ # @example Validates a key so it has to be a box.
128
+ # @validator.box(:a_box)
129
+ def box(key, options = {})
130
+ before_all(key, options)
131
+ match?(key, /^(?:[+-]?\d{1,3}(?:\.\d{1,7})?,?){4}$/) ? store_box(key, options) : raise_type_error(key, "Box")
132
+ end
133
+
134
+ # Checks if the given key is an email or not.
135
+ # @param [Object] key the key about which verify the type.
136
+ # @param [Hash] options a hash of options passed to this method (see documentation to know which options pass).
137
+ # @example Validates a key so it has to be an email.
138
+ # @validator.email(:email)
139
+ def email(key, options = {})
140
+ before_all(key, options)
141
+ match?(key, /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) ? store(key, ->(item){item}, options) : raise_type_error(key, "Email")
142
+ end
143
+
123
144
  private
124
145
 
125
146
  # This method is executed before any call to a public method.
@@ -192,6 +213,16 @@ module Kharon
192
213
  store(key, process, options)
193
214
  end
194
215
 
216
+ def store_box(key, options)
217
+ if(options.has_key?(:at_least))
218
+ box_contains?(datas[key], options[:at_least])
219
+ end
220
+ if(options.has_key?(:at_most))
221
+ box_contains?(options[:at_most], datas[key])
222
+ end
223
+ store(key, ->(item){parse_box(datas[key])}, options)
224
+ end
225
+
195
226
  # Checks if a required key is present in provided datas.
196
227
  # @param [Object] key the key of which check the presence.
197
228
  # @raise [ArgumentError] if the key is not present.
@@ -310,6 +341,32 @@ module Kharon
310
341
  end
311
342
  end
312
343
 
344
+ # Parses a box given as a string of four numbers separated by commas.
345
+ # @param [String] box the string representing the box.
346
+ # @return [Array] an array of size 2, containing two arrays of size 2 (the first being the coordinates of the top-left corner, the second the ones of the bottom-right corner)
347
+ def parse_box(box)
348
+ if box.kind_of?(String)
349
+ begin
350
+ raw_box = box.split(",").map(&:to_f)
351
+ box = [[raw_box[0], raw_box[1]], [raw_box[2], raw_box[3]]]
352
+ rescue
353
+ raise_error("The box was not correctly formatted")
354
+ end
355
+ end
356
+ return box
357
+ end
358
+
359
+ # Verify if a box contains another box.
360
+ # @param [Object] container any object that can be treated as a box, container of the other box
361
+ # @param [Object] contained any object that can be treated as a box, contained in the other box
362
+ # @return [Boolean] TRUE if the box is contained in the other one, FALSE if not.
363
+ def box_contains?(container, contained)
364
+ container = parse_box(container)
365
+ contained = parse_box(contained)
366
+ result = ((container[0][0] <= contained[0][0]) and (container[0][1] <= container[0][1]) and (container[1][0] >= container[1][0]) and (container[1][1] >= container[1][1]))
367
+ raise_error("The box #{contained} was supposed to be contained in #{container}") unless result
368
+ end
369
+
313
370
  # Raises a type error with a generic message.
314
371
  # @param [Object] key the key associated from the value triggering the error.
315
372
  # @param [Class] type the expected type, not respected by the initial value.
@@ -320,6 +377,9 @@ module Kharon
320
377
 
321
378
  protected
322
379
 
380
+ # Raises an error giving a message to display.
381
+ # @param [String] message the the message to display with the exception.
382
+ # @raises ArgumentError an error to stop the execution when this method is invoked.
323
383
  def raise_error(message)
324
384
  raise ArgumentError.new(message)
325
385
  end
@@ -0,0 +1,3 @@
1
+ module Kharon
2
+ VERSION = "0.4.0"
3
+ end
@@ -488,4 +488,99 @@ describe "Validator" do
488
488
  end
489
489
  end
490
490
 
491
+ context "box" do
492
+ let(:valid_datas) { {is_a_box: "-2,-2.0,100,100.0"} }
493
+ let(:valid_filtered) { {is_a_box: [[-2, -2], [100, 100]]} }
494
+ let(:invalid_datas) { {is_not_a_box: "anything else"} }
495
+
496
+ before do
497
+ @validator = Kharon::Validator.new(valid_datas)
498
+ end
499
+
500
+ it "succeeds when given a valid box" do
501
+ @validator.box(:is_a_box)
502
+ expect(@validator.filtered).to eq(valid_filtered)
503
+ end
504
+
505
+ it "fails when not given a box" do
506
+ validator = Kharon::Validator.new(invalid_datas)
507
+ expect(->{validator.box(:is_not_a_box)}).to raise_error(ArgumentError)
508
+ end
509
+
510
+ it "fails with an invalid top longitude" do
511
+ validator = Kharon::Validator.new(is_an_invalid_box: "test,12,12.0,-12.0")
512
+ expect(->{validator.box(:is_an_invalid_box)}).to raise_error(ArgumentError)
513
+ end
514
+
515
+ it "fails with an invalid top latitude" do
516
+ validator = Kharon::Validator.new(is_an_invalid_box: "0,test,12.0,-12.0")
517
+ expect(->{validator.box(:is_an_invalid_box)}).to raise_error(ArgumentError)
518
+ end
519
+
520
+ it "fails with an invalid down longitude" do
521
+ validator = Kharon::Validator.new(is_an_invalid_box: "0,12,test,-12.0")
522
+ expect(->{validator.box(:is_an_invalid_box)}).to raise_error(ArgumentError)
523
+ end
524
+
525
+ it "fails with an invalid down latitude" do
526
+ validator = Kharon::Validator.new(is_an_invalid_box: "0,12,12.0,test")
527
+ expect(->{validator.box(:is_an_invalid_box)}).to raise_error(ArgumentError)
528
+ end
529
+
530
+ context "options" do
531
+ include_examples "options", :box
532
+
533
+ context ":at_least" do
534
+
535
+ it "succeeds if the box is bigger than the one given with the at_least option" do
536
+ expect(->{@validator.box(:is_a_box, at_least: [[10, 10], [20, 20]])}).to_not raise_error
537
+ end
538
+
539
+ it "succeeds if the box is equal than the one given with the at_least option" do
540
+ expect(->{@validator.box(:is_a_box, at_least: [[-2, -2], [100, 100]])}).to_not raise_error
541
+ end
542
+
543
+ it "fails if the box is smaller than the one given with the at_least option" do
544
+ expect(->{@validator.box(:is_a_box, at_least: [[-20, -20], [1000, 1000]])}).to raise_error(ArgumentError)
545
+ end
546
+ end
547
+
548
+ context "at_most" do
549
+
550
+ it "succeeds if the box is smaller than the one given with the at_most option" do
551
+ expect(->{@validator.box(:is_a_box, at_most: [[-20, -20], [1000, 1000]])}).to_not raise_error
552
+ end
553
+
554
+ it "succeeds if the box is equal than the one given with the at_most option" do
555
+ expect(->{@validator.box(:is_a_box, at_most: [[-2, -2], [100, 100]])}).to_not raise_error
556
+ end
557
+
558
+ it "fails if the box is bigger than the one given with the at_most option" do
559
+ expect(->{@validator.box(:is_a_box, at_most: [[10, 10], [20, 20]])}).to raise_error(ArgumentError)
560
+ end
561
+ end
562
+ end
563
+ end
564
+
565
+ context "email" do
566
+ let(:valid_datas) { {is_an_email: "vincent.courtois@mycar-innovations.com"} }
567
+ let(:valid_filtered) { valid_datas }
568
+ let(:invalid_datas) { {is_not_an_email: "anything else"} }
569
+
570
+ it "succeeds when given a valid email" do
571
+ validator = Kharon::Validator.new(valid_datas)
572
+ validator.email(:is_an_email)
573
+ expect(validator.filtered).to eq(valid_filtered)
574
+ end
575
+
576
+ it "fails when not given a email" do
577
+ validator = Kharon::Validator.new(invalid_datas)
578
+ expect(->{validator.email(:is_not_an_email)}).to raise_error(ArgumentError)
579
+ end
580
+
581
+ context "options" do
582
+ include_examples "options", :email
583
+ end
584
+ end
585
+
491
586
  end
@@ -1,9 +1,7 @@
1
+ require 'bundler/setup'
2
+ Bundler.setup
3
+
1
4
  # Sets the environment variable to test before loading all the files.
2
5
  ENV['RACK_ENV'] = 'test'
3
6
 
4
- require 'rack/test'
5
- require 'bson'
6
-
7
- require './lib/cool_validator.rb'
8
- require './lib/validator_factory.rb'
9
- require './lib/validator.rb'
7
+ require "kharon"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kharon
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.1
4
+ version: 0.4.0
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors:
@@ -16,7 +16,7 @@ dependencies:
16
16
  requirement: !ruby/object:Gem::Requirement
17
17
  none: false
18
18
  requirements:
19
- - - '='
19
+ - - ! '>='
20
20
  - !ruby/object:Gem::Version
21
21
  version: 2.2.2
22
22
  type: :runtime
@@ -24,7 +24,7 @@ dependencies:
24
24
  version_requirements: !ruby/object:Gem::Requirement
25
25
  none: false
26
26
  requirements:
27
- - - '='
27
+ - - ! '>='
28
28
  - !ruby/object:Gem::Version
29
29
  version: 2.2.2
30
30
  description: Kharon is a ruby hash validator that helps you fix the structure of a
@@ -34,14 +34,25 @@ executables: []
34
34
  extensions: []
35
35
  extra_rdoc_files: []
36
36
  files:
37
- - lib/validator.rb
38
- - lib/validate.rb
39
- - lib/validator_factory.rb
40
- - lib/cool_validator.rb
37
+ - .rspec
38
+ - Gemfile
39
+ - Gemfile.lock
40
+ - LICENSE
41
+ - README.md
42
+ - kharon-0.0.1.gem
43
+ - kharon-0.0.2.gem
44
+ - kharon-0.0.3.gem
45
+ - kharon-0.1.0.gem
46
+ - kharon-0.2.0.gem
47
+ - kharon-0.3.0.gem
48
+ - kharon-0.3.1.gem
49
+ - kharon.gemspec
50
+ - lib/kharon.rb
51
+ - lib/kharon/helpers/validate.rb
52
+ - lib/kharon/validator.rb
53
+ - lib/kharon/version.rb
54
+ - spec/lib/kharon/validator_spec.rb
41
55
  - spec/spec_helper.rb
42
- - spec/lib/validator_spec.rb
43
- - spec/lib/cool_validator_spec.rb
44
- - spec/lib/validator_factory_spec.rb
45
56
  homepage: https://rubygems.org/gems/kharon
46
57
  licenses:
47
58
  - Apache License 2
@@ -69,6 +80,5 @@ specification_version: 3
69
80
  summary: Ruby Hash validator
70
81
  test_files:
71
82
  - spec/spec_helper.rb
72
- - spec/lib/validator_spec.rb
73
- - spec/lib/cool_validator_spec.rb
74
- - spec/lib/validator_factory_spec.rb
83
+ - spec/lib/kharon/validator_spec.rb
84
+ has_rdoc:
@@ -1,32 +0,0 @@
1
- require "./lib/validator.rb"
2
-
3
- module Kharon
4
- # This validator is really cooler than the other one. It will help you validate datas without raising exception, if you don't want to.
5
- # @author Vincent Courtois <vincent.courtois@mycar-innovations.com>
6
- class CoolValidator < Kharon::Validator
7
-
8
- # @!attribute [r] errors
9
- # @return an array of strings, each string representing an error occured while validating the hash.
10
- attr_reader :errors
11
-
12
- # Constructor of the classe, receiving the datas to validate and filter.
13
- # @param [Hash] datas the datas to validate in the validator.
14
- # @example create a new instance of validator.
15
- # @validator = Kharon::CoolValidator.new({key: "value"})
16
- def initialize(datas)
17
- super(datas)
18
- @errors = Array.new
19
- end
20
-
21
- # Fancy method to see if the validator have seen an error in the given hash.
22
- def has_errors?
23
- return (@errors.empty? ? false : true)
24
- end
25
-
26
- protected
27
-
28
- def raise_error(message)
29
- errors.push(message)
30
- end
31
- end
32
- end
@@ -1,34 +0,0 @@
1
- require "./lib/validator.rb"
2
- require "./lib/cool_validator.rb"
3
-
4
- module Kharon
5
- module Factory
6
-
7
- # @!attribute [r|w] use_exceptions
8
- # @return TRUE if Kharon currently use exceptions, FALSE if not.
9
- @@use_exceptions = true
10
-
11
- # Acts as a creation method for validators, considering the options you transmitted.
12
- # @param [Hash] datas the datas to validate in the validator.
13
- def self.validator(datas)
14
- @@use_exceptions ? Kharon::Validator.new(datas) : Kharon::CoolValidator.new(datas)
15
- end
16
-
17
- # Allows you to pass a whole block to configure the Kharon module.
18
- # @param [Hash] block a block of configuration instructions to pass to the module. See documentation for further informations.
19
- def self.configure(&block)
20
- self.instance_eval(&block)
21
- end
22
-
23
- # Sets the use of exceptions in the whole process.
24
- # @param [Boolean] status TRUE if you want to use the eceptions, FALSE if not.
25
- def self.use_exceptions(status)
26
- @@use_exceptions = status
27
- end
28
-
29
- # Fancy method to know if the module uses the exceptions or not.
30
- def self.uses_exceptions?
31
- return @@use_exceptions
32
- end
33
- end
34
- end
@@ -1,24 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe "CoolValidator" do
4
- context "handling errors" do
5
-
6
- before do
7
- @validator = Kharon::CoolValidator.new({key: "value"})
8
- end
9
-
10
- it "doesn't raise an exception when an error occurs" do
11
- expect(->{@validator.any(:another, required: true)}).to_not raise_error
12
- end
13
-
14
- it "has an error when an error has occured" do
15
- @validator.any(:another, required: true)
16
- expect(@validator.has_errors?).to be(true)
17
- end
18
-
19
- it "doesn't have an error when none has occured" do
20
- @validator.any(:key, required: true)
21
- expect(@validator.has_errors?).to be(false)
22
- end
23
- end
24
- end
@@ -1,33 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe "Kharon::Factory" do
4
-
5
- context "validator" do
6
- it "produces a Kharon::Validator when exceptions are wanted" do
7
- Kharon::Factory.use_exceptions(true)
8
- expect(Kharon::Factory.validator({key: "value"})).to be_a(Kharon::Validator)
9
- end
10
-
11
- it "produces a Kharon::CoolValidator when exceptions are not wanted" do
12
- Kharon::Factory.use_exceptions(false)
13
- expect(Kharon::Factory.validator({key: "value"})).to be_a(Kharon::CoolValidator)
14
- end
15
- end
16
-
17
- context "configure" do
18
- it "correctly configures the module to use exceptions" do
19
- Kharon::Factory.configure do |configuration|
20
- configuration.use_exceptions(true)
21
- end
22
- expect(Kharon::Factory.uses_exceptions?).to be(true)
23
- end
24
-
25
- it "correctly configures the module to not use exceptions" do
26
- Kharon::Factory.configure do |configuration|
27
- configuration.use_exceptions(false)
28
- end
29
- expect(Kharon::Factory.uses_exceptions?).to be(false)
30
- end
31
- end
32
-
33
- end