Class: Cooklang::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/cooklang/timer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration:, unit:, name: nil) ⇒ Timer

Returns a new instance of Timer.



7
8
9
10
11
# File 'lib/cooklang/timer.rb', line 7

def initialize(duration:, unit:, name: nil)
  @name = name&.to_s&.freeze
  @duration = duration
  @unit = unit&.to_s&.freeze
end

Instance Attribute Details

#durationObject (readonly)

Returns the value of attribute duration.



5
6
7
# File 'lib/cooklang/timer.rb', line 5

def duration
  @duration
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/cooklang/timer.rb', line 5

def name
  @name
end

#unitObject (readonly)

Returns the value of attribute unit.



5
6
7
# File 'lib/cooklang/timer.rb', line 5

def unit
  @unit
end

Instance Method Details

#==(other) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/cooklang/timer.rb', line 28

def ==(other)
  return false unless other.is_a?(Timer)

  name == other.name &&
    duration == other.duration &&
    unit == other.unit
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/cooklang/timer.rb', line 36

def eql?(other)
  self == other
end

#has_name?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/cooklang/timer.rb', line 61

def has_name?
  !@name.nil?
end

#hashObject



40
41
42
# File 'lib/cooklang/timer.rb', line 40

def hash
  [name, duration, unit].hash
end

#to_hObject



20
21
22
23
24
25
26
# File 'lib/cooklang/timer.rb', line 20

def to_h
  {
    name: @name,
    duration: @duration,
    unit: @unit
  }.compact
end

#to_sObject



13
14
15
16
17
18
# File 'lib/cooklang/timer.rb', line 13

def to_s
  result = ""
  result += "#{@name}: " if @name
  result += "#{@duration} #{@unit}"
  result
end

#total_secondsObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/cooklang/timer.rb', line 44

def total_seconds
  return @duration unless @unit

  case @unit.downcase
  when "second", "seconds", "sec", "s"
    @duration
  when "minute", "minutes", "min", "m"
    @duration * 60
  when "hour", "hours", "hr", "h"
    @duration * 3600
  when "day", "days", "d"
    @duration * 86_400
  else
    @duration
  end
end