Sha256: 1398e59fc4cf737fc47d1764030676af44cd8350478176eb7f480c13f28d8905

Contents?: true

Size: 898 Bytes

Versions: 1

Compression:

Stored size: 898 Bytes

Contents

class Parser
  PATTERN = Regexp.new(
    '(?i)((?<start_time>[0-9]{1,2}:?[0-9]{0,2}?)\s?(?<start_period>am|pm)?\s?(-|until)\s?)?(?<end_time>[0-9]{1,2}:?[0-9]{0,2})?\s?(?<end_period>am|pm)\s?(?<time_zone>[a-z][sd]t)?\b',
    Regexp::IGNORECASE
  ).freeze

  def initialize(text, date: Date.current)
    @text = text
    @date = date
  end

  def call
    result = PATTERN.match(@text)
    return nil unless result

    match_result = MatchResult.new(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
  end

  private

  def time_from_string(string)
    time_parser.parse("#{@date.to_s(:db)} #{string}")
  end

  def time_parser
    ::Time.zone ? ::Time.zone : ::Time
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
time_range_extractor-0.1.1 lib/time_range_extractor/parser.rb