Class: Typed::Validations::FieldTypeValidator

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Includes:
FieldValidator
Defined in:
lib/typed/validations/field_type_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate(field:, value:) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/typed/validations/field_type_validator.rb', line 11

def validate(field:, value:)
  if field.works_with?(value)
    Success.new(ValidatedValue.new(name: field.name, value:))
  elsif field.required? && value.nil?
    Failure.new(RequiredFieldError.new(field_name: field.name))
  elsif field.optional? && value.nil?
    if field.default.nil?
      Success.new(ValidatedValue.new(name: field.name, value:))
    else
      Success.new(ValidatedValue.new(name: field.name, value: field.default))
    end
  else
    Failure.new(TypeMismatchError.new(field_name: field.name, field_type: field.type, given_type: value.class))
  end
end