st_validation 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7d05c5f917d6f84aa0156cde50c68081d41d0fc8328723008785c6056e3a9bf4
4
+ data.tar.gz: bff39f336727f38a08f86f7ad8b282e9d610937cb4cb0ef564c302bef826abe5
5
+ SHA512:
6
+ metadata.gz: '0768162330257a317bbbc80b75ebafabbf8282784ee4a81d39cf1556672856b4c977fffc77e0e207c6556e707961a6781e4c258c765f336ee4624a31d4737959'
7
+ data.tar.gz: 02e9b0e68e2ca20cb0a89a3f3e366dbd7c141bd33170331a1c4c7849df5101af9d10df32e475ed87f695065ec02ee9accb677a0231668c53a7419c41ec5e21d0
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.5.3
7
+ before_install: gem install bundler -v 2.0.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in st_validation.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Dmitry Non
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.org ADDED
@@ -0,0 +1,193 @@
1
+ #+TITLE: St. Validation
2
+
3
+ Incredibly simple and customisable validation DSL
4
+
5
+ #+BEGIN_SRC ruby
6
+ is_valid_user = StValidation.build(
7
+ id: Integer,
8
+ name: String,
9
+ age: ->(x) { x.is_a?(Integer) && (0..150).cover?(x) },
10
+ favourite_food: [String],
11
+ dog: Set[NilClass, { name: String, age: Integer, breed: Set[NilClass, String] }]
12
+ )
13
+
14
+ is_valid_user.call(
15
+ id: 123,
16
+ name: 'John',
17
+ age: 18,
18
+ favourite_food: %w[apples pies],
19
+ dog: { name: 'Lucky', age: 2 }
20
+ )
21
+
22
+ # ===> true
23
+ #+END_SRC
24
+
25
+ * Table of Contents <-- :TOC: -->
26
+ - [[#installation][Installation]]
27
+ - [[#usage][Usage]]
28
+ - [[#terms][Terms]]
29
+ - [[#basic-syntax][Basic syntax]]
30
+ - [[#classes][Classes]]
31
+ - [[#sets-unions][Sets (unions)]]
32
+ - [[#arrays][Arrays]]
33
+ - [[#hashes][Hashes]]
34
+ - [[#when-we-dont-care-about-additional-keys][When we don't care about additional keys]]
35
+ - [[#misc][Misc]]
36
+ - [[#boolean][Boolean]]
37
+ - [[#maybe-optional-values][Maybe (optional values)]]
38
+ - [[#tinkering-dsl][Tinkering DSL]]
39
+ - [[#important-note][Important note!]]
40
+ - [[#contributing][Contributing]]
41
+ - [[#license][License]]
42
+
43
+ * Installation
44
+
45
+ #+BEGIN_SRC ruby
46
+ gem 'st_validation'
47
+ #+END_SRC
48
+
49
+ * Usage
50
+
51
+ ** Terms
52
+
53
+ - *validator* - proc-predicate or an object from
54
+ `StValidation::AbstractValidator` family and used for validating an object.
55
+ This is what you want to get from this gem in the end.
56
+ - *factory* - refers to a `StValidation::ValidatorFactory` and transforms
57
+ /blueprints/ into /validators/ by given set of /transformations/.
58
+ - *blueprint* - a validator or something that can be transformed into a
59
+ validator by factory.
60
+ - *transformation* - function =f(blueprint, factory)= returning a
61
+ /blueprint/. The core of the DSL itself.
62
+
63
+ ** Basic syntax
64
+
65
+ All of these are blueprints. Some of them are composable, e.g arrays and
66
+ hashes.
67
+
68
+ *** Classes
69
+
70
+ By using a class as a blueprint the result validator will check if an object
71
+ belongs to the class.
72
+
73
+ #+BEGIN_SRC ruby
74
+ is_int = StValidation.build(Integer)
75
+ is_int.call(123) # ==> true
76
+ is_int.call('123') # ==> false
77
+ #+END_SRC
78
+
79
+ *** Sets (unions)
80
+
81
+ Checks if a value matches /any/ provided blueprint.
82
+
83
+ #+BEGIN_SRC ruby
84
+ is_str_or_int = Set[String, Integer]
85
+ is_str_or_int.call(123) # ==> true
86
+ is_str_or_int.call('123') # ==> true
87
+ #+END_SRC
88
+
89
+ *** Arrays
90
+
91
+ Arrays are defined via =[<blueprint>]=. The result validator checks if its
92
+ every element matches =blueprint=. Note that array should be of /exactly/ one element.
93
+
94
+ #+BEGIN_SRC ruby
95
+ is_bool_array = StValidation.build([Set[TrueClass, FalseClass]])
96
+ is_bool_array.call(true) # ==> false
97
+ is_bool_array.call([]) # ==> true
98
+ is_bool_array.call([false]) # ==> true
99
+ #+END_SRC
100
+
101
+ *** Hashes
102
+
103
+ Quite naturally, hashes just check if every key matches a blueprint.
104
+
105
+ #+BEGIN_SRC ruby
106
+ is_user = StValidation.build(
107
+ id: Integer,
108
+ email: String,
109
+ info: { first_name: String,
110
+ last_name: String }
111
+ )
112
+ #+END_SRC
113
+
114
+ **** When we don't care about additional keys
115
+
116
+ There's a =HashSubsetValidator= for that. It checks only provided keys.
117
+
118
+ #+BEGIN_SRC ruby
119
+ is_user = StValidation::Validators::HashSubsetValidator.new(
120
+ id: Integer,
121
+ email: String,
122
+ info: { first_name: String,
123
+ last_name: String }
124
+ )
125
+
126
+ is_user.call(
127
+ id: 123,
128
+ email: 'user@example.com',
129
+ info: { first_name: 'John', last_name: 'Doe' },
130
+ phone: '+123456',
131
+ notes: 'Loves beer'
132
+ )
133
+ # ==> true
134
+ #+END_SRC
135
+
136
+ *** Misc
137
+
138
+ **** Boolean
139
+
140
+ Ruby doesn't have a class for bool value.
141
+ Instead, it has =TrueClass= and =FalseClass= which we can use with in a set:
142
+
143
+ #+BEGIN_SRC ruby
144
+ is_bool = Set[TrueClass, FalseClass]
145
+ #+END_SRC
146
+
147
+ **** Maybe (optional values)
148
+
149
+ Again, sets are to rescue:
150
+
151
+ #+BEGIN_SRC ruby
152
+ maybe_int = Set[NilClass, Integer]
153
+ #+END_SRC
154
+
155
+ ** Tinkering DSL
156
+
157
+ The ultimate goal of the factory is to return a validator.
158
+ In order to generate a validator from a blueprint is to /transform/ it.
159
+
160
+ Factory instance has a collection of transformations.
161
+ Each of them is applied to a blueprint until there's no transformations done.
162
+
163
+ Let's introduce some sugar syntax for booleans.
164
+
165
+ #+BEGIN_SRC ruby
166
+ factory = StValidation.with_extra_transformations(
167
+ ->(bp, factory) { bp == :bool ? Set[TrueClass, FalseClass] : bp }
168
+ )
169
+
170
+ is_user = factory.build(
171
+ name: String,
172
+ loves_beer: :bool
173
+ )
174
+
175
+ is_user.call(name: 'John Doe', loves_beer: true) # ==> true
176
+ #+END_SRC
177
+
178
+ *** Important note!
179
+
180
+ A blueprint goes through *all* transformations.
181
+ The process stops when no transformation changed the blueprint.
182
+
183
+ Do *not* rely on order; it's not guarantueed.
184
+
185
+
186
+ * Contributing
187
+
188
+ Bug reports and pull requests are welcome on GitHub at
189
+ https://github.com/Nondv/st_validation.rb
190
+
191
+ * License
192
+
193
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "st_validation"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,11 @@
1
+ module StValidation
2
+ class AbstractValidator
3
+ def call
4
+ raise 'implement this'
5
+ end
6
+
7
+ def to_proc
8
+ ->(x) { call(x) }
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,4 @@
1
+ module StValidation
2
+ class Error < StandardError; end
3
+ class InvalidBlueprintError < StValidation::Error; end
4
+ end
@@ -0,0 +1,22 @@
1
+ module StValidation
2
+ class ValidatorFactory
3
+ attr_reader :transformations
4
+
5
+ def initialize(transformations = [])
6
+ @transformations = transformations
7
+ end
8
+
9
+ def build(blueprint)
10
+ result = blueprint
11
+ loop do
12
+ old = result
13
+ result = transformations.reduce(result) { |res, t| t.call(res, self) }
14
+ break if result == old
15
+ end
16
+
17
+ raise InvalidBlueprintError unless result.is_a?(Proc) || result.is_a?(AbstractValidator)
18
+
19
+ result
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,17 @@
1
+ require_relative '../abstract_validator'
2
+
3
+ module StValidation
4
+ module Validators
5
+ class ArrayValidator < AbstractValidator
6
+ def initialize(element_blueprint, factory)
7
+ @validator = factory.build(element_blueprint)
8
+ end
9
+
10
+ def call(value)
11
+ return false unless value.is_a?(Array)
12
+
13
+ value.all?(&@validator)
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,15 @@
1
+ require_relative '../abstract_validator'
2
+
3
+ module StValidation
4
+ module Validators
5
+ class ClassValidator < AbstractValidator
6
+ def initialize(klass)
7
+ @klass = klass
8
+ end
9
+
10
+ def call(value)
11
+ value.is_a?(@klass)
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,24 @@
1
+ require_relative '../abstract_validator'
2
+ require_relative 'hash_validator'
3
+
4
+ module StValidation
5
+ module Validators
6
+ # Use this when you don't care if there're extra keys set
7
+ class HashSubsetValidator < AbstractValidator
8
+ def initialize(blueprint, factory = StValidation.basic_factory)
9
+ @keys = blueprint.keys
10
+ @hash_validator = StValidation::Validators::HashValidator.new(blueprint, factory)
11
+ end
12
+
13
+ def call(value)
14
+ return false unless value.is_a?(Hash)
15
+
16
+ @hash_validator.call(value.slice(*keys))
17
+ end
18
+
19
+ private
20
+
21
+ attr_reader :keys, :hash_validator
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,23 @@
1
+ require_relative '../abstract_validator'
2
+
3
+ module StValidation
4
+ module Validators
5
+ class HashValidator < AbstractValidator
6
+ def initialize(blueprint, factory)
7
+ @validators = blueprint.map { |k, bp| [k, factory.build(bp)] }.to_h
8
+ end
9
+
10
+ def call(value)
11
+ return false unless value.is_a?(Hash) &&
12
+ (value.keys - validators.keys).empty?
13
+
14
+ validators.each { |k, v| return false unless v.call(value[k]) }
15
+ true
16
+ end
17
+
18
+ private
19
+
20
+ attr_reader :validators
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,21 @@
1
+ require_relative '../abstract_validator'
2
+
3
+ module StValidation
4
+ module Validators
5
+ ##
6
+ # Checks if a value matches any of given blueprints
7
+ #
8
+ class UnionValidator < AbstractValidator
9
+ def initialize(blueprint_list, factory)
10
+ # TODO: I think it's better to raise a different kind of error and transform it later
11
+ raise InvalidBlueprintError if blueprint_list.empty?
12
+
13
+ @validators = blueprint_list.map { |bp| factory.build(bp) }
14
+ end
15
+
16
+ def call(value)
17
+ @validators.any? { |v| v.call(value) }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,3 @@
1
+ module StValidation
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,51 @@
1
+ require 'set'
2
+
3
+ require_relative "st_validation/version"
4
+ require_relative "st_validation/errors"
5
+ require_relative 'st_validation/validator_factory'
6
+
7
+ Dir[File.join(__dir__, 'st_validation', 'validators', '*.rb')].each { |file| require file }
8
+
9
+ module StValidation
10
+ class << self
11
+ def build(blueprint)
12
+ basic_factory.build(blueprint)
13
+ end
14
+
15
+ def with_extra_transformations(*transformations)
16
+ all_transformations = transformations + basic_transformations
17
+ StValidation::ValidatorFactory.new(all_transformations)
18
+ end
19
+
20
+ def basic_factory
21
+ StValidation::ValidatorFactory.new(basic_transformations)
22
+ end
23
+
24
+ private
25
+
26
+ def basic_transformations
27
+ [
28
+ ->(bp, _factory) { bp.is_a?(Class) ? class_validator(bp) : bp },
29
+ ->(bp, factory) { bp.is_a?(Set) ? union_validator(bp, factory) : bp },
30
+ ->(bp, factory) { bp.is_a?(Hash) ? hash_validator(bp, factory) : bp },
31
+ ->(bp, factory) { bp.is_a?(Array) && bp.size == 1 ? array_validator(bp[0], factory) : bp }
32
+ ]
33
+ end
34
+
35
+ def class_validator(klass)
36
+ Validators::ClassValidator.new(klass)
37
+ end
38
+
39
+ def union_validator(blueprint, factory)
40
+ Validators::UnionValidator.new(blueprint, factory)
41
+ end
42
+
43
+ def array_validator(blueprint, factory)
44
+ Validators::ArrayValidator.new(blueprint, factory)
45
+ end
46
+
47
+ def hash_validator(blueprint, factory)
48
+ Validators::HashValidator.new(blueprint, factory)
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,27 @@
1
+ lib = File.expand_path("lib", __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "st_validation/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "st_validation"
7
+ spec.version = StValidation::VERSION
8
+ spec.authors = ["Dmitry Non"]
9
+ spec.email = ["mail@nondv.io"]
10
+
11
+ spec.summary = 'Yet another validation library'
12
+ spec.homepage = 'https://github.com/Nondv/st_validation.rb'
13
+ spec.license = "MIT"
14
+
15
+ # Specify which files should be added to the gem when it is released.
16
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
17
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
18
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 2.0"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+ end
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: st_validation
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dmitry Non
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-12-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.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
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description:
56
+ email:
57
+ - mail@nondv.io
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.org
68
+ - Rakefile
69
+ - bin/console
70
+ - bin/setup
71
+ - lib/st_validation.rb
72
+ - lib/st_validation/abstract_validator.rb
73
+ - lib/st_validation/errors.rb
74
+ - lib/st_validation/validator_factory.rb
75
+ - lib/st_validation/validators/array_validator.rb
76
+ - lib/st_validation/validators/class_validator.rb
77
+ - lib/st_validation/validators/hash_subset_validator.rb
78
+ - lib/st_validation/validators/hash_validator.rb
79
+ - lib/st_validation/validators/union_validator.rb
80
+ - lib/st_validation/version.rb
81
+ - st_validation.gemspec
82
+ homepage: https://github.com/Nondv/st_validation.rb
83
+ licenses:
84
+ - MIT
85
+ metadata: {}
86
+ post_install_message:
87
+ rdoc_options: []
88
+ require_paths:
89
+ - lib
90
+ required_ruby_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: '0'
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '0'
100
+ requirements: []
101
+ rubyforge_project:
102
+ rubygems_version: 2.7.6
103
+ signing_key:
104
+ specification_version: 4
105
+ summary: Yet another validation library
106
+ test_files: []