Class: Data::Validator
- Inherits:
-
Object
- Object
- Data::Validator
- Defined in:
- lib/data/validator.rb,
lib/data/validator.rb
Class Method Summary collapse
- .bare_new ⇒ Object
-
.new(rule) ⇒ Object
Creates a new validator.
Instance Method Summary collapse
-
#initialize(rule = {}) ⇒ Validator
constructor
(Maybe recursively) constructs a validator.
-
#validate(actual = @isa.new) ⇒ Object
Validates the input.
-
#with(extension) ⇒ Object
add options.
Constructor Details
#initialize(rule = {}) ⇒ Validator
(Maybe recursively) constructs a validator.
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/data/validator.rb', line 78 def initialize(rule = {}) @isa = rule.delete(:isa) || Object # ?? @rule = rule if rule.has_key? :rule then raise TypeError, "rule must be a hash" unless rule[:rule].is_a? Hash case when @isa == Hash then recur = rule[:rule].each_pair.each_with_object Hash.new do |(k, v), r| case v when Hash then r[k] = self.class.send :bare_new, v else r[k] = self.class.send :bare_new, isa: v end end @rule = rule.merge rule: recur when @isa == Array then recur = self.class.new rule[:rule] @rule = rule.merge rule: recur end end end |
Class Method Details
.bare_new ⇒ Object
29 |
# File 'lib/data/validator.rb', line 29 alias new |
.new(hash) ⇒ Data::Validator .new(array) ⇒ Data::Validator .new(validator) ⇒ Data::Validator .new(object) ⇒ Data::Validator
Creates a new validator.
59 60 61 62 63 64 65 66 |
# File 'lib/data/validator.rb', line 59 def new rule case rule when self then rule # already when Hash then isa: Hash, rule: rule when Array then isa: Array, rule: rule else isa: rule end end |
Instance Method Details
#validate(actual = @isa.new) ⇒ Object
Note:
this does not modify the validator, but does modify the argument object.
Validates the input
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/data/validator.rb', line 108 def validate actual = @isa.new case actual when *@isa then if @rule.has_key? :rule then case when @isa == Hash then return validate_hash actual when @isa == Array then return validate_array actual else raise RuntimeError, "[bug] notreached" end else return actual end else raise Error, "type mismatch" end end |
#with(extension) ⇒ Object
add options
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/data/validator.rb', line 127 def with extension case extension when 'AllowExtra' then @rule[:allow_extra] = true if @rule.has_key? :rule case when @isa == Hash then @rule[:rule].each_value do |rule| rule.with extension if rule.is_a? self.class end else @rule[:rule].with extension if @rule[:rule].is_a? self.class end end else raise ArgumentError, "unsupported extension #{extension}" end return self end |