Class: Objecheck::Validator::KeyValueRule
- Inherits:
-
Object
- Object
- Objecheck::Validator::KeyValueRule
- Defined in:
- lib/objecheck/validator/key_value_rule.rb
Overview
KeyValueRule validates key/value in the target by using each_pair
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(validator, key_value_schema) ⇒ KeyValueRule
constructor
A new instance of KeyValueRule.
- #validate(target, collector) ⇒ Object
Constructor Details
#initialize(validator, key_value_schema) ⇒ KeyValueRule
Returns a new instance of KeyValueRule.
20 21 22 23 24 25 26 27 |
# File 'lib/objecheck/validator/key_value_rule.rb', line 20 def initialize(validator, key_value_schema) @key_value_rules = key_value_schema.each_with_object({}) do |(key, schema), rules| rules[key] = { required: schema.fetch(:required, true), rule: validator.compile_schema(schema[:value]) } end end |
Class Method Details
.schema ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/objecheck/validator/key_value_rule.rb', line 46 def self.schema [ { type: Hash, each_value: { type: Hash, key_value: { required: { required: false, value: { type: :bool } }, value: { value: { type: Hash } } } } } ] end |
Instance Method Details
#validate(target, collector) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/objecheck/validator/key_value_rule.rb', line 29 def validate(target, collector) if !target.respond_to?(:each_pair) collector.add_error('should respond to `each_pair`') return end @key_value_rules.each_pair do |key, rule| if target.key?(key) collector.add_prefix_in("[#{key.inspect}]") do collector.validate(target[key], rule[:rule]) end elsif rule[:required] collector.add_error("should contain key #{key.inspect}") end end end |