Class: FortyTime

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

Direct Known Subclasses

NullFortyTime

Defined Under Namespace

Classes: ParseError

Constant Summary collapse

VERSION =
'0.0.8'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(minutes) ⇒ FortyTime

Returns a new instance of FortyTime.



30
31
32
# File 'lib/forty_time.rb', line 30

def initialize(minutes)
  @minutes = minutes
end

Instance Attribute Details

#minutesObject Also known as: value

Returns the value of attribute minutes.



26
27
28
# File 'lib/forty_time.rb', line 26

def minutes
  @minutes
end

Class Method Details

.parse(input) ⇒ Object

Raises:



8
9
10
11
12
13
14
15
16
17
# File 'lib/forty_time.rb', line 8

def self.parse(input)
  return NullFortyTime.new if input.nil? || input == ''
  return new(input) if input.is_a? Integer

  can_parse_string = input.is_a?(String) && input.match?(/:/)
  raise ParseError unless can_parse_string

  minutes = parse_string(input)
  new(minutes)
end

.parse_string(string) ⇒ Object



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

def self.parse_string(string)
  hours, extra = string.split(':').map(&:to_i)
  extra *= -1 if string[0] == '-'

  (hours * 60) + extra
end

Instance Method Details

#+(other) ⇒ Object



34
35
36
37
# File 'lib/forty_time.rb', line 34

def +(other)
  result = @minutes + other.minutes
  FortyTime.new(result)
end

#-(other) ⇒ Object



39
40
41
42
# File 'lib/forty_time.rb', line 39

def -(other)
  result = @minutes - other.minutes
  FortyTime.new(result)
end

#to_sObject



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/forty_time.rb', line 44

def to_s
  hours = (@minutes / 60.0).to_i
  extra = (@minutes - (hours * 60.0)).to_i

  if @minutes.negative?
    hours *= -1
    extra *= -1
    hours = "-#{hours}"
  end

  extra = "0#{extra}" if extra < 10
  [hours, extra].join(':')
end