Sha256: 70487ff3e8ce23f29bd6234e89061efe276666f34ebedd96867c19c9a18119b1

Contents?: true

Size: 1.14 KB

Versions: 10

Compression:

Stored size: 1.14 KB

Contents

module OpenActive
  module Validators
    class DateTimeValidator < BaseValidator
      # 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.
      #
      # @param value [mixed] The value to coerce.
      # @return [mixed] The same value.
      def coerce(value)
        return value if value.is_a?(::DateTime)

        # if it's a date/time object other than datetime, convert it (Date/Time)
        return value.to_datetime if value.respond_to?(:to_datetime)

        parse_date(value)
      end

      # Run validation on the given value.
      #
      # @param value [mixed] The value to validate.
      # @return [Boolean] Whether validation passes or not.
      def run(value)
        return true if value.is_a?(::DateTime) || value.respond_to?(:to_datetime)

        return false unless value.is_a?(String)

        !parse_date(value).nil?
      end

      private

      def parse_date(value)
        DateTime.parse(value)
      rescue ArgumentError => _e
        nil
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
openactive-0.5.0 lib/openactive/validators/date_time_validator.rb
openactive-0.4.0 lib/openactive/validators/date_time_validator.rb
openactive-0.3.0 lib/openactive/validators/date_time_validator.rb
openactive-0.2.2 lib/openactive/validators/date_time_validator.rb
openactive-0.2.1 lib/openactive/validators/date_time_validator.rb
openactive-0.2.0 lib/openactive/validators/date_time_validator.rb
openactive-0.1.2 lib/openactive/validators/date_time_validator.rb
openactive-0.1.1 lib/openactive/validators/date_time_validator.rb
openactive-0.1.0 lib/openactive/validators/date_time_validator.rb
openactive-0.1.0.rc1 lib/openactive/validators/date_time_validator.rb