Class: Typed::Coercion::DateTimeCoercer

Inherits:
Coercer
  • Object
show all
Extended by:
T::Generic
Defined in:
lib/typed/coercion/date_time_coercer.rb

Constant Summary collapse

Target =
type_member { {fixed: DateTime} }

Instance Method Summary collapse

Instance Method Details

#coerce(type:, value:) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/typed/coercion/date_time_coercer.rb', line 18

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

#used_for_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/typed/coercion/date_time_coercer.rb', line 13

def used_for_type?(type)
  T::Utils.coerce(type) == T::Utils.coerce(DateTime)
end