Class: ClockTime

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/clock_time.rb

Defined Under Namespace

Classes: Span

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hour, min) ⇒ ClockTime

Returns a new instance of ClockTime.



19
20
21
22
23
24
25
# File 'lib/clock_time.rb', line 19

def initialize(hour, min)
  @hour = hour
  @minute = min
  if !valid_hour? || !valid_minute?
    raise ArgumentError, 'invalid clock time'
  end
end

Instance Attribute Details

#hourObject (readonly)

Returns the value of attribute hour.



7
8
9
# File 'lib/clock_time.rb', line 7

def hour
  @hour
end

#minuteObject (readonly)

Returns the value of attribute minute.



7
8
9
# File 'lib/clock_time.rb', line 7

def minute
  @minute
end

Class Method Details

.parse(string) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/clock_time.rb', line 10

def parse(string)
  if string =~ /\A(\d{2})[^\d]?(\d{2})\z/
    new($1.to_i, $2.to_i)
  else
    raise ArgumentError, 'invalid clock time'
  end
end

Instance Method Details

#+(augend) ⇒ Object



56
57
58
59
60
61
# File 'lib/clock_time.rb', line 56

def +(augend)
  if augend.is_a?(self.class)
    augend = augend.to_duration
  end
  to_duration + augend
end

#-(minuend) ⇒ Object



63
64
65
66
67
68
# File 'lib/clock_time.rb', line 63

def -(minuend)
  if minuend.is_a?(self.class)
    minuend = minuend.to_duration
  end
  to_duration - minuend
end

#<=>(clock_time) ⇒ Object



52
53
54
# File 'lib/clock_time.rb', line 52

def <=>(clock_time)
  to_duration <=> clock_time.to_duration
end

#next_time(base_time) ⇒ Object



36
37
38
39
40
# File 'lib/clock_time.rb', line 36

def next_time(base_time)
  t = replace_time(base_time)
  return t + 1.day if t < base_time
  t
end

#prev_time(base_time) ⇒ Object



42
43
44
45
46
# File 'lib/clock_time.rb', line 42

def prev_time(base_time)
  t = replace_time(base_time)
  return t - 1.day if t > base_time
  t
end

#replace_time(time) ⇒ Object



48
49
50
# File 'lib/clock_time.rb', line 48

def replace_time(time)
  time.change(hour: @hour, min: @minute)
end

#to_durationObject



27
28
29
# File 'lib/clock_time.rb', line 27

def to_duration
  @hour.hours + @minute.minutes
end

#to_time(date) ⇒ Object



31
32
33
34
# File 'lib/clock_time.rb', line 31

def to_time(date)
  midnight = date.to_time
  replace_time(midnight)
end

#valid_hour?Boolean

Returns:

  • (Boolean)


70
71
72
73
74
# File 'lib/clock_time.rb', line 70

def valid_hour?
  return false unless @hour.is_a?(Integer)
  return true if @hour >= 0 && @hour <= 24
  false
end

#valid_minute?Boolean

Returns:

  • (Boolean)


76
77
78
79
80
# File 'lib/clock_time.rb', line 76

def valid_minute?
  return false unless @minute.is_a?(Integer)
  return true if @minute >= 0 && @minute <= 60
  false
end