holamendi
6/24/2013 - 2:15 PM

How to generate a human readable time range using ruby on rails

How to generate a human readable time range using ruby on rails

# modification of http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails
def humanize_seconds secs, precision = 2
  return unless secs
  units = [[60, :second], [60, :minute], [24, :hour], [1000, :day]]
  diffs = units.map do |count, name|
    next if units.find_index([count, name]) > precision
    if secs > 0
      secs, n = secs.divmod(count)
      pluralize(n.to_i, name.to_s) if n > 0
    end
  end.compact.reverse
  diffs = diffs[0 .. precision - 1] if precision
  diffs.to_sentence
end