Module: CMDx::Coercions::DateTime

Extended by:
DateTime
Included in:
DateTime
Defined in:
lib/cmdx/coercions/date_time.rb

Overview

Coerces to ‘DateTime`. Pass `strptime:` to parse via a specific format; otherwise `DateTime.parse` is used for strings, and `#to_datetime` for any other responding object.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ DateTime, Coercions::Failure

Parameters:

  • value (Object)
  • options (Hash{Symbol => Object}) (defaults to: EMPTY_HASH)

Options Hash (options):

  • :strptime (String)

    format string for ‘DateTime.strptime`

Returns:



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cmdx/coercions/date_time.rb', line 16

def call(value, options = EMPTY_HASH)
  if value.is_a?(::DateTime)
    value
  elsif value.is_a?(::String)
    if (strptime = options[:strptime])
      ::DateTime.strptime(value, strptime)
    else
      ::DateTime.parse(value)
    end
  elsif value.respond_to?(:to_datetime)
    value.to_datetime
  else
    coercion_failure
  end
rescue ArgumentError, TypeError, ::Date::Error
  coercion_failure
end