Created
June 24, 2013 14:15
-
-
Save eljojo/5850360 to your computer and use it in GitHub Desktop.
How to generate a human readable time range using ruby on rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment