Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module DurationHelper
- # Takes a number of seconds as input and returns a formatted string. See
- # tests for examples.
- def format_duration(seconds, options = {})
- return "0 seconds" if seconds.floor == 0
- options.reverse_merge!(:parts_to_show => 4, :word_style => :short, :specific_end => false)
- description = (options[:word_style] == :short) ?
- [ ['sec', 60], ['min', 60], ['hr', 24], ['day'] ] :
- [ ['second', 60], ['minute', 60], ['hour', 24], ['day'] ]
- components = []
- units = seconds.floor
- description.each do |component, max|
- if max
- components.unshift([units % max, component])
- break unless units >= max
- units = units.to_f / max
- else
- components.unshift([units, component])
- end
- end
- parts_shown = 0
- results = components.map do |c|
- next if parts_shown >= options[:parts_to_show]
- parts_shown += 1
- number = c.first
- if options[:specific_end].present? && parts_shown == options[:parts_to_show] && c.last =~ /^(hr|hour|day)/
- number = number.round_at(1).to_i_if_whole
- else
- number = number.floor
- end
- next if number == 0
- "#{number} #{number == 1 ? c.last : c.last.pluralize}"
- end
- results.compact.join(' ')
- end
- end
Add Comment
Please, Sign In to add comment