Module: TimeDuration

Defined in:
lib/time_units/duration.rb

Class Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.unitsObject

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.

Parameters:

  • limit (Integer, nil) (defaults to: nil)

    if set this will limit the number of fields shown (ex: 2 = 2 months 3 weeks)

Returns:

  • (String)

    the formatted duration



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