Class: OpenActive::Validators::DateIntervalValidator

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

Instance Method Summary collapse

Methods inherited from BaseValidator

get_validator

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.

Raises:

  • (::Exception)

    When value cannot be parsed as a ::DateInterval



11
12
13
14
15
16
17
# File 'lib/openactive/validators/date_interval_validator.rb', line 11

def coerce(value)
  return value if value.is_a?(ActiveSupport::Duration)

  # If not passing a DateInterval object, try and create one from value
  # Assuming that the string will be an interval spec in ISO 8601 format
  ActiveSupport::Duration.parse(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.



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/openactive/validators/date_interval_validator.rb', line 23

def run(value)
  return true if value.is_a?(ActiveSupport::Duration)

  # If not a string - fail validation
  return false unless value.is_a?(String)

  begin
    ActiveSupport::Duration.parse(value)
    true
  rescue ArgumentError => _e
    false
  end
end