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.

Constant Summary collapse

ANALOG_TYPES =

Types that are already date-like and don’t need conversion

%w[Date DateTime Time].freeze

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ 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: {})

    Optional configuration parameters

Options Hash (options):

  • :strptime (String)

    Custom date format string for parsing

Returns:

  • (Date)

    The converted Date object

Raises:



40
41
42
43
44
45
46
47
48
# File 'lib/cmdx/coercions/date.rb', line 40

def call(value, options = {})
  return value if ANALOG_TYPES.include?(value.class.name)
  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