Class: Tins::Duration
- Includes:
- Comparable
- Defined in:
- lib/tins/duration.rb
Instance Method Summary collapse
- #<=>(other) ⇒ Object
- #days? ⇒ Boolean
- #format(template = '%S%d+%h:%m:%s.%f', precision: nil) ⇒ Object
- #fractional_seconds? ⇒ Boolean
- #hours? ⇒ Boolean
-
#initialize(seconds) ⇒ Duration
constructor
A new instance of Duration.
- #minutes? ⇒ Boolean
- #negative? ⇒ Boolean
- #seconds? ⇒ Boolean
- #to_f ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(seconds) ⇒ Duration
Returns a new instance of Duration.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/tins/duration.rb', line 5 def initialize(seconds) @negative = seconds < 0 seconds = seconds.abs @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
25 26 27 |
# File 'lib/tins/duration.rb', line 25 def <=>(other) to_f <=> other.to_f end |
#days? ⇒ Boolean
33 34 35 |
# File 'lib/tins/duration.rb', line 33 def days? @days > 0 end |
#format(template = '%S%d+%h:%m:%s.%f', precision: nil) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/tins/duration.rb', line 53 def format(template = '%S%d+%h:%m:%s.%f', precision: nil) result = template.gsub(/%[DdhmSs]/) { |directive| case directive when '%S' then ?- if negative? when '%d' then @days when '%h' then '%02u' % @hours when '%m' then '%02u' % @minutes when '%s' then '%02u' % @seconds when '%D' then format_smart end } 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
49 50 51 |
# File 'lib/tins/duration.rb', line 49 def fractional_seconds? @fractional_seconds > 0 end |
#hours? ⇒ Boolean
37 38 39 |
# File 'lib/tins/duration.rb', line 37 def hours? @hours > 0 end |
#minutes? ⇒ Boolean
41 42 43 |
# File 'lib/tins/duration.rb', line 41 def minutes? @minutes > 0 end |
#negative? ⇒ Boolean
29 30 31 |
# File 'lib/tins/duration.rb', line 29 def negative? @negative end |
#seconds? ⇒ Boolean
45 46 47 |
# File 'lib/tins/duration.rb', line 45 def seconds? @seconds > 0 end |
#to_f ⇒ Object
21 22 23 |
# File 'lib/tins/duration.rb', line 21 def to_f @original_seconds.to_f end |
#to_s ⇒ Object
75 76 77 |
# File 'lib/tins/duration.rb', line 75 def to_s format_smart end |