Created
November 30, 2012 12:22
-
-
Save remvee/4175478 to your computer and use it in GitHub Desktop.
Function to create strings like "6d 4h 1h 34m 23s" from an amount of seconds.
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
| # human_readable_seconds: | |
| # s: "%{s}s" | |
| # ms: "%{m}m %{s}s" | |
| # hms: "%{h}h %{m}m %{s}s" | |
| # dhms: "%{d}d %{h}h %{m}m %{s}s" | |
| def human_readable_seconds(seconds) | |
| attrs = {s: 60, m: 60, h: 24, d: nil}.reduce([1, {}]) do |(multiplier,result),(key,modulo)| | |
| if seconds / multiplier > 0 | |
| if modulo | |
| [multiplier * modulo, {key => (seconds / multiplier) % modulo}.merge(result)] | |
| else | |
| [multiplier, {key => (seconds / multiplier)}.merge(result)] | |
| end | |
| else | |
| [multiplier, result] | |
| end | |
| end.last | |
| I18n.t("human_readable_seconds.#{attrs.keys.join}", attrs) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment