Class: Tins::Duration

Inherits:
Object show all
Includes:
Comparable
Defined in:
lib/tins/duration.rb

Instance Method Summary collapse

Constructor Details

#initialize(seconds) ⇒ Duration

Returns a new instance of Duration.



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/tins/duration.rb', line 5

def initialize(seconds)
  @original_seconds = seconds
  @days, @hours, @minutes, @seconds, @fractional_seconds =
    [ 86_400, 3600, 60, 1, 0 ].inject([ [], seconds ]) {|(r, s), d|
      if d > 0
        dd, rest = s.divmod(d)
        r << dd
        [ r, rest ]
      else
        r << s
      end
    }
end

Instance Method Details

#<=>(other) ⇒ Object



23
24
25
# File 'lib/tins/duration.rb', line 23

def <=>(other)
  to_f <=> other.to_f
end

#days?Boolean

Returns:

  • (Boolean)


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

def days?
  @days > 0
end

#format(template = '%d+%h:%m:%s.%f', precision: nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tins/duration.rb', line 47

def format(template = '%d+%h:%m:%s.%f', precision: nil)
  result = template.gsub(/%[dhms]/,
    '%d' => @days,
    '%h' => '%02u' % @hours,
    '%m' => '%02u' % @minutes,
    '%s' => '%02u' % @seconds,
  )
  if result.include?('%f')
    if precision
      fractional_seconds = "%.#{precision}f" % @fractional_seconds
    else
      fractional_seconds = '%f' % @fractional_seconds
    end
    result.gsub!('%f', fractional_seconds[2..-1])
  end
  result
end

#fractional_seconds?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/tins/duration.rb', line 43

def fractional_seconds?
  @fractional_seconds > 0
end

#hours?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/tins/duration.rb', line 31

def hours?
  @hours > 0
end

#minutes?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/tins/duration.rb', line 35

def minutes?
  @minutes > 0
end

#seconds?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/tins/duration.rb', line 39

def seconds?
  @seconds > 0
end

#to_fObject



19
20
21
# File 'lib/tins/duration.rb', line 19

def to_f
  @original_seconds.to_f
end

#to_sObject



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tins/duration.rb', line 65

def to_s
  template  = '%h:%m:%s'
  precision = nil
  if days?
    template.prepend '%d+'
  end
  if fractional_seconds?
    template << '.%f'
    precision = 3
  end
  format template, precision: precision
end