Class: Numeric

Inherits:
Object show all
Defined in:
lib/aromat/duration.rb

Overview

Monkey-patch Numeric Class

Instance Method Summary collapse

Instance Method Details

#duration(elements = 10) ⇒ String

Duration: Produce textual representation of time duration.

Parameters:

  • elements (Fixnum) (defaults to: 10)

    Maximum number of time-elements (days, hours, minutes, etc…) to display

Returns:

  • (String)

    A String representing the duration like “14 Days 3 Minutes 21 Seconds”



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/aromat/duration.rb', line 11

def duration elements = 10

  # Compute Elements
  rest, secs = self.divmod 60
  rest, mins = rest.divmod 60
  rest, hours = rest.divmod 24
  rest, days = rest.divmod 7
  years, weeks = rest.divmod 52

  # Prep Result
  result = []
  (result << "#{years} Year#{(years > 1) ? 's' : ''}"; elements = elements - 1) if (years > 0) && (elements > 0)
  (result << "#{weeks} Week#{(weeks > 1) ? 's' : ''}"; elements = elements - 1) if (weeks > 0) && (elements > 0)
  (result << "#{days} Day#{(days > 1) ? 's' : ''}"; elements = elements - 1) if (days > 0) && (elements > 0)
  (result << "#{hours} Hour#{(hours > 1) ? 's' : ''}"; elements = elements - 1) if (hours > 0) && (elements > 0)
  (result << "#{mins} Minute#{(mins > 1) ? 's' : ''}"; elements = elements - 1) if (mins > 0) && (elements > 0)
  (result << "#{secs} Second#{(secs > 1) ? 's' : ''}"; elements = elements - 1) if (secs > 0) && (elements > 0)
  result.join ' '
end