class Apes::Validators::TimestampValidator
Validates timestamps.
Public Class Methods
Creates a new validator.
@param options [Hash] The options for the validations. @return [Apes::Validators::TimestampValidator] A new validator.
# File lib/apes/validators.rb, line 221 def initialize(options) super(options.reverse_merge(default_message: "must be a valid ISO 8601 timestamp")) end
Parses a timestamp value according to a list of formats.
@param value [Object] The value to parse. @param formats [Array|NilClass] A list of valid formats (see strftime). Will fallback to formats defined in Rails configuration. @param raise_errors [Boolean] Whether to raise errors in case the value couldn't be parsed with any format. @return [DateTime|NilClass] A `DateTime` if parsing succeded, `nil` otherwise.
# 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
Parses a timestamp without raising exceptions.
@param value [String] The value to parse. @return [DateTime|NilClass] A `DateTime` if parsing succeded, `nil` otherwise.
# File lib/apes/validators.rb, line 211 def self.safe_parse(value, format) DateTime.strptime(value, format) rescue nil end
Public Instance Methods
Checks if the value is valid for this validator.
@param value [Object] The value to validate. @return [Boolean] `true` if the value is valid, false otherwise.
# File lib/apes/validators.rb, line 229 def check_valid?(value) value.blank? || TimestampValidator.parse(value, formats: options[:formats]) end