Sha256: 7306923366b6d56eb9b6e31ab6ce92b33bf76d0c64a6c4548cd827b51728965f

Contents?: true

Size: 841 Bytes

Versions: 5

Compression:

Stored size: 841 Bytes

Contents

# typed: strict

require "date"

module Typed
  module Coercion
    class DateTimeCoercer < Coercer
      extend T::Generic

      Target = type_member { {fixed: DateTime} }

      sig { override.params(type: T::Types::Base).returns(T::Boolean) }
      def used_for_type?(type)
        T::Utils.coerce(type) == T::Utils.coerce(DateTime)
      end

      sig { override.params(type: T::Types::Base, value: Value).returns(Result[Target, CoercionError]) }
      def coerce(type:, value:)
        return Failure.new(CoercionError.new("Type must be a DateTime.")) unless used_for_type?(type)

        return Success.new(value) if value.is_a?(DateTime)

        Success.new(DateTime.parse(value))
      rescue Date::Error, TypeError
        Failure.new(CoercionError.new("'#{value}' cannot be coerced into DateTime."))
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
sorbet-schema-0.9.2 lib/typed/coercion/date_time_coercer.rb
sorbet-schema-0.9.1 lib/typed/coercion/date_time_coercer.rb
sorbet-schema-0.9.0 lib/typed/coercion/date_time_coercer.rb
sorbet-schema-0.8.0 lib/typed/coercion/date_time_coercer.rb
sorbet-schema-0.7.2 lib/typed/coercion/date_time_coercer.rb