Class: Tins::Duration
Instance Method Summary collapse
- #days? ⇒ Boolean
- #format(template = '%d+%h:%m:%s.%f', precision: nil) ⇒ Object
- #fractional_seconds? ⇒ Boolean
- #hours? ⇒ Boolean
-
#initialize(seconds) ⇒ Duration
constructor
A new instance of Duration.
- #minutes? ⇒ Boolean
- #seconds? ⇒ Boolean
- #to_s ⇒ Object
Constructor Details
#initialize(seconds) ⇒ Duration
Returns a new instance of Duration.
3 4 5 6 7 8 9 10 11 12 13 14 |
# File 'lib/tins/duration.rb', line 3 def initialize(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
#days? ⇒ Boolean
16 17 18 |
# File 'lib/tins/duration.rb', line 16 def days? @days > 0 end |
#format(template = '%d+%h:%m:%s.%f', precision: nil) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/tins/duration.rb', line 36 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
32 33 34 |
# File 'lib/tins/duration.rb', line 32 def fractional_seconds? @fractional_seconds > 0 end |
#hours? ⇒ Boolean
20 21 22 |
# File 'lib/tins/duration.rb', line 20 def hours? @hours > 0 end |
#minutes? ⇒ Boolean
24 25 26 |
# File 'lib/tins/duration.rb', line 24 def minutes? @minutes > 0 end |
#seconds? ⇒ Boolean
28 29 30 |
# File 'lib/tins/duration.rb', line 28 def seconds? @seconds > 0 end |
#to_s ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/tins/duration.rb', line 54 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 |