Module: ChronicDuration
Instance Method Summary collapse
-
#output(seconds, opts = {}) ⇒ Object
Given an integer and an optional format, returns a formatted string representing elapsed time.
-
#parse(string) ⇒ Object
Given a string representation of elapsed time, return an integer (or float, if fractions of a second are input).
Instance Method Details
#output(seconds, opts = {}) ⇒ Object
Given an integer and an optional format, returns a formatted string representing elapsed time
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/chronic_duration.rb', line 15 def output(seconds, opts = {}) opts[:format] ||= :default years = months = days = hours = minutes = 0 if seconds >= 60 minutes = (seconds / 60).to_i seconds = seconds % 60 if minutes >= 60 hours = (minutes / 60).to_i minutes = (minutes % 60).to_i if hours >= 24 days = (hours / 24).to_i hours = (hours % 24).to_i if days >= 30 months = (days / 30).to_i days = (days % 30).to_i if months >= 12 years = (months / 12).to_i months = (months % 12).to_i end end end end end joiner = ' ' process = nil case opts[:format] when :short dividers = { :years => 'y', :months => 'm', :days => 'd', :hours => 'h', :minutes => 'm', :seconds => 's' } when :default dividers = { :years => ' yr', :months => ' mo', :days => ' day', :hours => ' hr', :minutes => ' min', :seconds => ' sec', :pluralize => true } when :long dividers = { :years => ' year', :months => ' month', :days => ' day', :hours => ' hour', :minutes => ' minute', :seconds => ' second', :pluralize => true } when :chrono dividers = { :years => ':', :months => ':', :days => ':', :hours => ':', :minutes => ':', :seconds => ':', :keep_zero => true } process = lambda do |str| # Pad zeros # Get rid of lead off times if they are zero # Get rid of lead off zero # Get rid of trailing : str.gsub(/\b\d\b/) { |d| ("%02d" % d) }.gsub(/^(00:)+/, '').gsub(/^0/, '').gsub(/:$/, '') end joiner = '' end result = [] [:years, :months, :days, :hours, :minutes, :seconds].each do |t| result << humanize_time_unit( eval(t.to_s), dividers[t], dividers[:pluralize], dividers[:keep_zero] ) end result = result.join(joiner).squeeze(' ').strip if process result = process.call(result) end result.length == 0 ? nil : result end |
#parse(string) ⇒ Object
Given a string representation of elapsed time, return an integer (or float, if fractions of a second are input)
8 9 10 11 |
# File 'lib/chronic_duration.rb', line 8 def parse(string) result = calculate_from_words(cleanup(string)) result == 0 ? nil : result end |