Module: CMDx::Coercions::Date

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

Overview

Converts various input types to Date format

Handles conversion from strings, Date objects, DateTime objects, Time objects, and other date-like values to Date objects using Ruby’s built-in parsing capabilities and optional custom format parsing.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Date

Converts a value to a Date object

Examples:

Convert string to Date using default parsing

Date.call("2023-12-25")           # => #<Date: 2023-12-25>
Date.call("Dec 25, 2023")        # => #<Date: 2023-12-25>

Convert string using custom format

Date.call("25/12/2023", strptime: "%d/%m/%Y")  # => #<Date: 2023-12-25>
Date.call("12-25-2023", strptime: "%m-%d-%Y")  # => #<Date: 2023-12-25>

Return existing Date objects unchanged

Date.call(Date.new(2023, 12, 25)) # => #<Date: 2023-12-25>
Date.call(DateTime.new(2023, 12, 25)) # => #<Date: 2023-12-25>

Parameters:

  • value (Object)

    The value to convert to a Date

  • options (Hash) (defaults to: EMPTY_HASH)

    Optional configuration parameters

Options Hash (options):

  • :strptime (String)

    Custom date format string for parsing

Returns:

  • (Date)

    The converted Date object

Raises:

Rbs:

  • (untyped value, ?Hash[Symbol, untyped] options) -> Date



35
36
37
38
39
40
41
42
43
# File 'lib/cmdx/coercions/date.rb', line 35

def call(value, options = EMPTY_HASH)
  return value.to_date if value.respond_to?(:to_date)
  return ::Date.strptime(value, options[:strptime]) if options[:strptime]

  ::Date.parse(value)
rescue TypeError, ::Date::Error
  type = Locale.t("cmdx.types.date")
  raise CoercionError, Locale.t("cmdx.coercions.into_a", type:)
end