Class: OpenActive::Validators::BaseValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/openactive/validators/base_validator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.get_validator(type) ⇒ ::OpenActive::Validators::ValidatorInterface

Returns a validator instance from a given type name.

Parameters:

  • type (string)

    The type name

Returns:

  • (::OpenActive::Validators::ValidatorInterface)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/openactive/validators/base_validator.rb', line 29

def self.get_validator(type) # rubocop:disable Metrics/MethodLength
  # If last 2 characters are "[]"
  # We are validating an array
  if type.end_with?('[]')
    # Build item validator name
    # (remove last 2 characters "[]")
    item_type = type[0...-2]

    # Instantiate validator
    return ArrayOfValidator.new(get_validator(item_type))
  end

  # If first letter of type is a lower case letter
  # We are validating a native type
  if type.match(/^[[:lower:]]/)
    # Build item validator name (FQ)
    class_name = "#{type.classify}Validator"
    validator = ::OpenActive::Validators.const_get(class_name)

    return validator.new
  end

  validator =
    case type
    when "URI"
      UriValidator.new
    when "Time"
      TimeValidator.new
    when "DateTime"
      DateTimeValidator.new
    when "DateInterval"
      DateIntervalValidator.new
    when "Number"
      NumberValidator.new
    end

  return validator if validator

  # everything beyond this we're dealing with actual classes.. hopefully
  klass = Object.const_get(type)

  return EnumValidator.new(klass) if klass.ancestors.include?(TypesafeEnum::Base)

  # If type is an OpenActive BaseModel class
  return BaseModelValidator.new if klass == OpenActive::JsonLdModel

  InstanceValidator.new(klass)
end

Instance Method Details

#coerce(value) ⇒ mixed

Coerce given value to the type the validator is validating against. PLEASE NOTE: no checks are performed on the given value. It is therefore recommended to call the “run” method first before this.

Parameters:

  • value (mixed)

    The value to coerce.

Returns:

  • (mixed)

    The same value.



10
11
12
13
14
15
# File 'lib/openactive/validators/base_validator.rb', line 10

def coerce(value)
  # For all the classes that inherit BaseValidator
  # that don't need to coerce,
  # This is a no-op
  value
end

#run(_value) ⇒ Boolean

Run validation on the given value.

Parameters:

  • _value (mixed)

    The value to validate.

Returns:

  • (Boolean)

    Whether validation passes or not.



21
22
23
# File 'lib/openactive/validators/base_validator.rb', line 21

def run(_value)
  false
end