Class: Mementus::Model::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/mementus/model/validator.rb

Overview

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

Current design raises errors 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



9
10
11
# File 'lib/mementus/model/validator.rb', line 9

def initialize(fields_spec)
  @spec = fields_spec
end

Instance Method Details

#check(fields) ⇒ Object

Checks a given set of fields to see if they match the specification.

Raises an error when the given fields are invalid.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/mementus/model/validator.rb', line 16

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