Class: Compel::Validators::TypeValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/compel/validators/type_validator.rb

Instance Attribute Summary

Attributes inherited from Base

#errors, #input, #output, #schema

Instance Method Summary collapse

Methods inherited from Base

#initialize, #valid?, validate

Constructor Details

This class inherits a constructor from Compel::Validators::Base

Instance Method Details

#validateObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/compel/validators/type_validator.rb', line 9

def validate
  if !schema.required? && input.nil?
    return self
  end

  # coerce
  coercion_result = Coercion.coerce(input, schema.type, schema.options)

  unless coercion_result.valid?
    @errors = [coercion_result.error]
    return self
  end

  @output = coercion_result.coerced

  # validate
  @errors = Validation.validate(@output, schema.type, schema.options)

  # validate array values
  if schema.type == Coercion::Array && errors.empty?
    validate_array_values(input)
  end

  self
end

#validate_array_values(values) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/compel/validators/type_validator.rb', line 35

def validate_array_values(values)
  result = Result.new \
    ArrayValidator.validate(values, schema)

  @output = result.value

  if !result.valid?
    # TODO: ArrayValidator should do this for me:
    # remove invalid coerced index,
    # and set the original value.
    # If it's an Hash, keep errors key
    result.errors.keys.each do |index|
      if @output[index.to_i].is_a?(Hash)
        # Keep errors key on hash if exists
        @output[index.to_i].merge!(values[index.to_i])
      else
        # Array, Integer, String, Float, Dates.. etc
        @output[index.to_i] = values[index.to_i]
      end
    end

    @errors = result.errors
  end
end