Class: FlycalCli::DurationParser

Inherits:
Object
  • Object
show all
Defined in:
lib/flycal_cli/duration_parser.rb

Constant Summary collapse

UNITS =
{
  "s" => :seconds, "sec" => :seconds, "second" => :seconds, "seconds" => :seconds,
  "m" => :minutes, "min" => :minutes, "mins" => :minutes, "minute" => :minutes, "minutes" => :minutes,
  "h" => :hours, "hr" => :hours, "hour" => :hours, "hours" => :hours,
  "d" => :days, "day" => :days, "days" => :days,
  "w" => :weeks, "week" => :weeks, "weeks" => :weeks,
  "month" => :months, "months" => :months,
  "y" => :years, "year" => :years, "years" => :years
}.freeze

Class Method Summary collapse

Class Method Details

.add_to_time(str, from_time) ⇒ Object



44
45
46
# File 'lib/flycal_cli/duration_parser.rb', line 44

def add_to_time(str, from_time)
  from_time + parse(str)
end

.parse(str) ⇒ Object

Raises:



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/flycal_cli/duration_parser.rb', line 19

def parse(str)
  normalized = str.to_s.strip.downcase
  match = normalized.match(/\A(\d+(?:\.\d+)?)\s*([a-z]+)\z/) ||
          normalized.match(/\A(\d+(?:\.\d+)?)([a-z]+)\z/)
  raise FlycalCli::Error, invalid_message(str) unless match

  value = match[1].to_f
  unit_key = match[2]
  unit = UNITS[unit_key]
  raise FlycalCli::Error, invalid_message(str) unless unit
  # Ambiguous bare "m": treat as minutes (not months)
  unit = :minutes if unit_key == "m"

  # months/years are Integer-only ActiveSupport extensions
  if %i[months years].include?(unit)
    value.to_i.public_send(unit)
  else
    value.public_send(unit)
  end
end

.to_seconds(str) ⇒ Object



40
41
42
# File 'lib/flycal_cli/duration_parser.rb', line 40

def to_seconds(str)
  parse(str).to_i
end