Class: Apes::Validators::TimestampValidator

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

Overview

Validates timestamps.

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from BaseValidator

#validate_each

Constructor Details

- (Apes::Validators::TimestampValidator) initialize(options)

Creates a new validator.

Parameters:

  • options (Hash)

    The options for the validations.



221
222
223
# File 'lib/apes/validators.rb', line 221

def initialize(options)
  super(options.reverse_merge(default_message: "must be a valid ISO 8601 timestamp"))
end

Class Method Details

+ (DateTime|NilClass) parse(value, formats: nil, raise_errors: false)

Parses a timestamp value according to a list of formats.

Parameters:

  • value (Object)

    The value to parse.

  • formats (Array|NilClass)

    A list of valid formats (see strftime). Will fallback to formats defined in Rails configuration.

  • raise_errors (Boolean)

    Whether to raise errors in case the value couldn’t be parsed with any format.

Returns:

  • (DateTime|NilClass)

    A DateTime if parsing succeded, nil otherwise.

Raises:

  • (ArgumentError)


188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/apes/validators.rb', line 188

def self.parse(value, formats: nil, raise_errors: false)
  return value if [ActiveSupport::TimeWithZone, DateTime, Date, Time].include?(value.class)

  formats ||= Apes::RuntimeConfiguration.timestamp_formats.values.dup

  rv = catch(:valid) do
    formats.each do |format|
      parsed = safe_parse(value, format)

      throw(:valid, parsed) if parsed
    end

    nil
  end

  raise(ArgumentError, "Invalid timestamp \"#{value}\".") if !rv && raise_errors
  rv
end

+ (DateTime|NilClass) safe_parse(value, format)

Parses a timestamp without raising exceptions.

Parameters:

  • value (String)

    The value to parse.

Returns:

  • (DateTime|NilClass)

    A DateTime if parsing succeded, nil otherwise.



211
212
213
214
215
# File 'lib/apes/validators.rb', line 211

def self.safe_parse(value, format)
  DateTime.strptime(value, format)
rescue
  nil
end

Instance Method Details

- (Boolean) check_valid?(value)

Checks if the value is valid for this validator.

Parameters:

  • value (Object)

    The value to validate.

Returns:

  • (Boolean)

    true if the value is valid, false otherwise.



229
230
231
# File 'lib/apes/validators.rb', line 229

def check_valid?(value)
  value.blank? || TimestampValidator.parse(value, formats: options[:formats])
end