Class: Yarrow::Schema::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/yarrow/schema.rb

Overview

Checks values plugged into each slot and runs any required validations (validations not yet implemented).

Current design throws on error rather than returns a boolean result.

Instance Method Summary collapse

Constructor Details

#initialize(fields_spec) ⇒ Validator

Returns a new instance of Validator.

Parameters:

  • fields_spec (Hash)

    defines the slots in the schema to validate against



15
16
17
# File 'lib/yarrow/schema.rb', line 15

def initialize(fields_spec)
  @spec = fields_spec
end

Instance Method Details

#check(fields) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/yarrow/schema.rb', line 19

def check(fields)
  missing_fields = @spec.keys.difference(fields.keys)

  if missing_fields.any?
    missing_fields.each do |field|
      raise "wrong number of args" unless @spec[field].eql?(Type::Any)
    end
  end

  mismatching_fields = fields.keys.difference(@spec.keys)

  raise "key does not exist" if mismatching_fields.any?

  fields.each do |(field, value)|
    raise "wrong data type" unless value.is_a?(@spec[field]) || @spec[field].eql?(Type::Any)
  end

  true
end