Module: Dsu::Support::CommandOptions::Time

Defined in:
lib/dsu/support/command_options/time.rb

Overview

TODO: Make this into an ActiveModel class that uses validations.

The purpose of this module is to take a command option that is a string and return a Time object. The command option is expected to be a date in the format of [M]M/D. MM and DD with leading zeroes is optional (i.e. only M and D are required), YYYY is optionl and will be replaced with the current year if not provided.

Constant Summary collapse

DATE_CAPTURE_REGEX =
%r{\A(?<month>0?[1-9]|1[0-2])/(?<day>0?[1-9]|1\d|2\d|3[01])(?:/(?<year>\d{4}))?\z}

Class Method Summary collapse

Class Method Details

.time_from_date_string(command_option:) ⇒ Object



36
37
38
39
40
# File 'lib/dsu/support/command_options/time.rb', line 36

def time_from_date_string(command_option:)
  time_from_date_string!(command_option: command_option)
rescue ArgumentError
  nil
end

.time_from_date_string!(command_option:) ⇒ Object



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

def time_from_date_string!(command_option:)
  raise ArgumentError, 'command_option is nil.' if command_option.nil?
  raise ArgumentError, 'command_option is blank.' if command_option.blank?

  unless command_option.is_a?(String)
    raise ArgumentError, "command_option is not a String: \"#{command_option}\"."
  end

  time_parts = time_parts_for(time_string: command_option)
  return unless time_parts?(time_parts: time_parts)

  valid_time!(time_parts: time_parts)

  # This will rescue errors resulting from calling Date.strptime with an invalid date string,
  # and return a more meaningful error message.
rescue DateTime::Error
  raise ArgumentError, "command_option is not a valid date: \"#{command_option}\"."
end