module ServingSeconds::Core

Public Instance Methods

humanize(secs, prec = nil, format = nil) click to toggle source
# File lib/serving_seconds/core.rb, line 4
def humanize(secs, prec = nil, format = nil)
  prec, format = format, prec if prec && !prec.is_a?(Numeric)

  format ||= :short
  prec   ||= 0

  humanized = []

  intervals.each_with_index do |interval, i|
    units = send(interval)
    next unless secs >= units || units == seconds

    return find(secs, i, prec, format) if format == :short

    next if secs == 0

    secs = add_time_for_interval(humanized, secs, units, i, format)
  end

  humanized.join ', '
end

Private Instance Methods

add_time_for_interval(array, secs, units, i, format) click to toggle source
# File lib/serving_seconds/core.rb, line 43
def add_time_for_interval(array, secs, units, i, format)
  even = (secs / units).floor
  time = find(even * units, i, 0, format)
  array << (even == 1 ? time.chop : time)

  secs - units * even
end
days() click to toggle source
# File lib/serving_seconds/core.rb, line 74
def days
  @days ||= 24 * hours
end
find(secs, i, prec, format) click to toggle source
# File lib/serving_seconds/core.rb, line 28
def find(secs, i, prec, format)
  units = send(intervals[i])
  x = (secs / units).round(prec)
  if i - 1 >= 0 && x * units >= send(intervals[i - 1])
    return find(x * units, i - 1, prec, format)
  end

  descriptor = intervals[i]
  descriptor = format == :short ? descriptor[0] : descriptor

  joiner = format == :short ? '' : ' '

  [x, descriptor].join joiner
end
hours() click to toggle source
# File lib/serving_seconds/core.rb, line 70
def hours
  @hours ||= 60 * minutes
end
intervals() click to toggle source
# File lib/serving_seconds/core.rb, line 51
def intervals
  @intervals ||= [
    :years,
    :weeks,
    :days,
    :hours,
    :minutes,
    :seconds,
  ]
end
minutes() click to toggle source
# File lib/serving_seconds/core.rb, line 66
def minutes
  @minutes ||= 60 * seconds
end
seconds() click to toggle source
# File lib/serving_seconds/core.rb, line 62
def seconds
  @seconds ||= 1.to_f
end
weeks() click to toggle source
# File lib/serving_seconds/core.rb, line 78
def weeks
  @weeks ||= 7 * days
end
years() click to toggle source
# File lib/serving_seconds/core.rb, line 82
def years
  @years ||= 365 * days
end