Module: CMDx::Coercions::Date

Extended by:
Date
Included in:
Date
Defined in:
lib/cmdx/coercions/date.rb

Overview

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

Instance Method Summary collapse

Instance Method Details

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

Parameters:

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

Options Hash (options):

  • :strptime (String)

    format string for ‘Date.strptime`

Returns:



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

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