# frozen_string_literal: true # Parse out time values from a string of text. Uses the provided date as the # basis for the DateTime generation. class Parser PATTERN = / (\A|\s|\() # space or round bracket, to support: "Call Jim (8-9pm)" ( (?[1-2]?[0-9]:?[0-9]{2}?)\s? (?am|pm)?\s? (to|-|until)\s? )? (?[1-2]?[0-9]:?[0-9]{2}?)?\s? (?am|pm)\s? (?( [ABCDEFGHIJKLMNOPRSTUVWY] [A-Z] [ACDEGHKLMNORSTUVW]? [CDNSTW]? [T]? ))?\b /xi.freeze def initialize(text, date: Date.current) @text = text @date = date end def call match = PATTERN.match(@text) result = MatchResult.new(match) return nil unless result.valid? time_range_from(result) end private def time_range_from(match_result) start_time = time_from_string(match_result.start_time_string) end_time = time_from_string(match_result.end_time_string) if start_time <= end_time start_time..end_time elsif start_time > end_time start_time..(end_time + 1.day) end rescue ArgumentError nil end def time_from_string(string) time_parser.parse(string, @date.to_time) end # :reek:UtilityFunction so that we can optionally include ActiveSupport def time_parser ::Time.zone || ::Time end end