Class: Runby::RunbyTimeParser::TimeParts

Inherits:
Object
  • Object
show all
Defined in:
lib/runby_pace/runby_time_parser.rb

Overview

Encapsulates the parts of a time string

Instance Method Summary collapse

Constructor Details

#initialize(parts_array) ⇒ TimeParts

Returns a new instance of TimeParts.


45
46
47
48
49
50
51
# File 'lib/runby_pace/runby_time_parser.rb', line 45

def initialize(parts_array)
  @keys = { seconds: 0, minutes: 1, hours: 2 }
  @parts = Array.new(@keys.count, 0)
  Range.new(0, parts_array.count - 1).each { |i| @parts[i] = parts_array[i] }
  validate
  freeze
end

Instance Method Details

#[](key) ⇒ Object


53
54
55
56
# File 'lib/runby_pace/runby_time_parser.rb', line 53

def [](key)
  i = @keys[key]
  @parts[i].to_i
end

#formatObject


58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/runby_pace/runby_time_parser.rb', line 58

def format
  time_f = +''
  @parts.reverse_each do |part|
    time_f << ':' << part.to_s.rjust(2, '0')
  end
  # Remove leading ':'
  time_f.slice!(0)
  # Remove leading '00:00...'
  time_f.sub!(/^(?:00:)+(\d\d:\d\d)/, '\1') if time_f.length > 5
  # If the time looks like 00:48, only show 0:48
  time_f.slice!(0) if time_f.slice(0) == '0'
  time_f
end

#validateObject


72
73
74
75
76
77
# File 'lib/runby_pace/runby_time_parser.rb', line 72

def validate
  raise 'Hours must be less than 24' if self[:hours] > 23
  raise 'Minutes must be less than 60 if hours are supplied' if self[:hours].positive? && self[:minutes] > 59
  raise 'Minutes must be less than 99 if no hours are supplied' if self[:hours].zero? && self[:minutes] > 99
  raise 'Seconds must be less than 60' if self[:seconds] > 59
end