Guest User

Untitled

a guest
Apr 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. module DurationHelper
  2.  
  3. # Takes a number of seconds as input and returns a formatted string. See
  4. # tests for examples.
  5. def format_duration(seconds, options = {})
  6. return "0 seconds" if seconds.floor == 0
  7. options.reverse_merge!(:parts_to_show => 4, :word_style => :short, :specific_end => false)
  8.  
  9. description = (options[:word_style] == :short) ?
  10. [ ['sec', 60], ['min', 60], ['hr', 24], ['day'] ] :
  11. [ ['second', 60], ['minute', 60], ['hour', 24], ['day'] ]
  12.  
  13. components = []
  14. units = seconds.floor
  15. description.each do |component, max|
  16. if max
  17. components.unshift([units % max, component])
  18. break unless units >= max
  19. units = units.to_f / max
  20. else
  21. components.unshift([units, component])
  22. end
  23. end
  24.  
  25. parts_shown = 0
  26. results = components.map do |c|
  27. next if parts_shown >= options[:parts_to_show]
  28. parts_shown += 1
  29. number = c.first
  30. if options[:specific_end].present? && parts_shown == options[:parts_to_show] && c.last =~ /^(hr|hour|day)/
  31. number = number.round_at(1).to_i_if_whole
  32. else
  33. number = number.floor
  34. end
  35. next if number == 0
  36. "#{number} #{number == 1 ? c.last : c.last.pluralize}"
  37. end
  38. results.compact.join(' ')
  39. end
  40.  
  41. end
Add Comment
Please, Sign In to add comment