Module: TimeDuration
- Defined in:
- lib/time_units/duration.rb
Class Attribute Summary collapse
-
.units ⇒ Object
Returns the value of attribute units.
Instance Method Summary collapse
-
#human_duration(limit = nil) ⇒ String
Format a duration for display.
Class Attribute Details
.units ⇒ Object
Returns the value of attribute units.
4 5 6 |
# File 'lib/time_units/duration.rb', line 4 def units @units end |
Instance Method Details
#human_duration(limit = nil) ⇒ String
Format a duration for display.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/time_units/duration.rb', line 25 def human_duration(limit = nil) diff = Hash.new(0) ret = [] pluralize = proc do |count, arr| unit = (count == 1) ? arr[2] : arr[3] "#{count} #{unit}" end t = self.to_i while t > 0 TimeDuration.units.each do |(limit, field)| if t >= limit diff[field] += 1 t -= limit break end end end ret = [] TimeDuration.units.each.with_index do |unit| unit_name = unit[1] if diff[unit_name] > 0 ret << pluralize.(diff[unit_name], unit) if ret.size == limit break end end end ret.join(' ') end |