Class: Tins::Duration
- Includes:
- Comparable
- Defined in:
- lib/tins/duration.rb
Instance Method Summary collapse
- #<=>(other) ⇒ Object
- #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_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 |
# 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
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 64 65 66 |
# File 'lib/tins/duration.rb', line 47 def format(template = '%d+%h:%m:%s.%f', precision: nil) result = template.gsub(/%[Ddhms]/) { |directive| case directive 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
43 44 45 |
# File 'lib/tins/duration.rb', line 43 def fractional_seconds? @fractional_seconds > 0 end |
#hours? ⇒ Boolean
31 32 33 |
# File 'lib/tins/duration.rb', line 31 def hours? @hours > 0 end |
#minutes? ⇒ Boolean
35 36 37 |
# File 'lib/tins/duration.rb', line 35 def minutes? @minutes > 0 end |
#seconds? ⇒ Boolean
39 40 41 |
# File 'lib/tins/duration.rb', line 39 def seconds? @seconds > 0 end |
#to_f ⇒ Object
19 20 21 |
# File 'lib/tins/duration.rb', line 19 def to_f @original_seconds.to_f end |
#to_s ⇒ Object
68 69 70 |
# File 'lib/tins/duration.rb', line 68 def to_s format_smart end |