Module: CMDx::Coercions::Time

Extended by:
Time
Included in:
Time
Defined in:
lib/cmdx/coercions/time.rb

Overview

Coerces to ‘Time`. Strings use `Time.parse` (or `strptime` when supplied); Numerics are treated as epoch seconds; objects responding to `#to_time` are unwrapped.

Instance Method Summary collapse

Instance Method Details

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

Parameters:

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

Options Hash (options):

  • :strptime (String)

    format string for ‘Time.strptime`

Returns:



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

def call(value, options = EMPTY_HASH)
  if value.is_a?(::Time)
    value
  elsif value.is_a?(::String)
    if (strptime = options[:strptime])
      ::Time.strptime(value, strptime)
    else
      ::Time.parse(value)
    end
  elsif value.is_a?(::Numeric)
    ::Time.at(value)
  elsif value.respond_to?(:to_time)
    value.to_time
  else
    coercion_failure
  end
rescue ArgumentError, TypeError
  coercion_failure
end