Module: CMDx::Coercions::Time

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

Overview

Converts various input types to Time format

Handles conversion from strings, dates, and other time-like objects to Time using Ruby’s built-in time parsing methods. Supports custom strptime formats and raises CoercionError for values that cannot be converted to Time.

Constant Summary collapse

ANALOG_TYPES =

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

%w[DateTime Time].freeze

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ Time

Converts a value to a Time object

Examples:

Convert time-like objects

Time.call(Time.now)                    # => Time object (unchanged)
Time.call(DateTime.now)                # => Time object (converted)
Time.call(Date.today)                  # => Time object (converted)

Convert strings with default parsing

Time.call("2023-12-25 10:30:00")      # => Time object
Time.call("2023-12-25")               # => Time object
Time.call("10:30:00")                 # => Time object

Convert strings with custom format

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

Parameters:

  • value (Object)

    The value to convert to a Time object

  • options (Hash) (defaults to: {})

    Optional configuration parameters

Options Hash (options):

  • :strptime (String)

    Custom strptime format string for parsing

Returns:

  • (Time)

    The converted Time object

Raises:

  • (CoercionError)

    If the value cannot be converted to a Time object



42
43
44
45
46
47
48
49
50
51
# File 'lib/cmdx/coercions/time.rb', line 42

def call(value, options = {})
  return value if ANALOG_TYPES.include?(value.class.name)
  return value.to_time if value.respond_to?(:to_time)
  return ::Time.strptime(value, options[:strptime]) if options[:strptime]

  ::Time.parse(value)
rescue ArgumentError, TypeError
  type = Locale.t("cmdx.types.time")
  raise CoercionError, Locale.t("cmdx.coercions.into_a", type:)
end