Module: ATValidations::Predicates
- Defined in:
- lib/at-validations.rb
Instance Method Summary collapse
- #atv_array_of(predicate) ⇒ Object
- #atv_block(&b) ⇒ Object
- #atv_equal(value) ⇒ Object
- #atv_hash(mask, opts = {}) ⇒ Object
- #atv_in_set(*set) ⇒ Object
- #atv_instance_of(klass) ⇒ Object
- #atv_nil_or(predicate) ⇒ Object
- #atv_numeric ⇒ Object
- #atv_option(*predicates) ⇒ Object
- #atv_string ⇒ Object
- #atv_symbol ⇒ Object
- #atv_union(*predicates) ⇒ Object
Instance Method Details
#atv_array_of(predicate) ⇒ Object
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/at-validations.rb', line 54 def atv_array_of(predicate) atv_union( atv_instance_of(Array), atv_block do |e| errs = {} e.each_index {|i| err = predicate.call(e); errs[i] = err unless true == err } errs.count == 0 || Error.new(:error => 'array contains elements which do not match predicate', :failures => errs) end ) end |
#atv_block(&b) ⇒ Object
32 33 34 |
# File 'lib/at-validations.rb', line 32 def atv_block(&b) b end |
#atv_equal(value) ⇒ Object
87 88 89 90 91 |
# File 'lib/at-validations.rb', line 87 def atv_equal(value) atv_block do |e| e == value || Error.new(:error => "must be equal to #{value}") end end |
#atv_hash(mask, opts = {}) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/at-validations.rb', line 36 def atv_hash(mask, opts = {}) atv_union( atv_instance_of(Hash), atv_block do |e| errors = {} mask.each do |k, v| r = v.call(e[k]) errors[k] = r unless true == r end if false == opts[:allow_extra] && (extra = (e.keys - mask.keys)).count > 0 extra.each {|k| errors[k] = 'is not present in predicate' } end errors.empty? || Error.new(:error => 'must match hash predicate', :failures => errors) end ) end |
#atv_in_set(*set) ⇒ Object
81 82 83 84 85 |
# File 'lib/at-validations.rb', line 81 def atv_in_set(*set) atv_block do |e| set.include?(e) || Error.new(:error => "must be in set #{set}") end end |
#atv_instance_of(klass) ⇒ Object
93 94 95 96 97 |
# File 'lib/at-validations.rb', line 93 def atv_instance_of(klass) atv_block do |e| e.is_a?(klass) || Error.new(:error => "must be a #{klass}") end end |
#atv_nil_or(predicate) ⇒ Object
111 112 113 114 115 |
# File 'lib/at-validations.rb', line 111 def atv_nil_or(predicate) atv_block do |e| nil == e || predicate.call(e) end end |
#atv_numeric ⇒ Object
99 100 101 |
# File 'lib/at-validations.rb', line 99 def atv_numeric atv_instance_of(Numeric) end |
#atv_option(*predicates) ⇒ Object
73 74 75 76 77 78 79 |
# File 'lib/at-validations.rb', line 73 def atv_option(*predicates) atv_block do |e| errs = [] nil != predicates.find {|p| true == (errs << p.call(e)).last } || Error.new(:error => 'must match at least one predicate in option', :failure => errs) end end |
#atv_string ⇒ Object
103 104 105 |
# File 'lib/at-validations.rb', line 103 def atv_string atv_instance_of(String) end |
#atv_symbol ⇒ Object
107 108 109 |
# File 'lib/at-validations.rb', line 107 def atv_symbol atv_instance_of(Symbol) end |