class Timing::Interval

Constants

CONVERSIONS
MULTIPLIER
REGEXP
UNITS
UNITS_NAMES

Public Class Methods

between(time_1, time_2) click to toggle source
# File lib/timing/interval.rb, line 42
def self.between(time_1, time_2)
  new (time_1 - time_2).round
end
new(seconds) click to toggle source
Calls superclass method
# File lib/timing/interval.rb, line 46
def initialize(seconds)
  raise ArgumentError, "#{seconds} is not a number" unless seconds.is_a? Numeric
  super seconds.abs
end
parse(expression) click to toggle source
# File lib/timing/interval.rb, line 32
def self.parse(expression)
  seconds = expression.split(' ').inject(0) do |total, value|
    match = REGEXP.match value.strip
    raise "Invalid interval expression #{expression}" unless match
    total + match.captures[0].to_f * CONVERSIONS[match.captures[1].to_sym]
  end

  new seconds
end

Public Instance Methods

begin_of(time) click to toggle source
# File lib/timing/interval.rb, line 63
def begin_of(time)
  normalized_time = time + time.utc_offset
  gap = normalized_time.to_i % self
  normalized_time - gap - time.utc_offset
end
end_of(time) click to toggle source
# File lib/timing/interval.rb, line 69
def end_of(time)
  begin_of(time) + self - 1
end
inspect() click to toggle source
# File lib/timing/interval.rb, line 96
def inspect
  "#{to_s} (#{to_seconds})"
end
to_human(options={}) click to toggle source
# File lib/timing/interval.rb, line 82
def to_human(options={})
  biggest_unit = options.fetch(:biggest_unit, :w)
  smallest_unit = options.fetch(:smallest_unit, :s)
  last_index = UNITS.index(biggest_unit.to_sym)
  first_index = UNITS.index(smallest_unit.to_sym)
  units = UNITS[first_index..last_index]
  representations = units.map.with_index do |unit, i|
    acumulate = (i != last_index - first_index)
    representation = to_representation(unit, acumulate)
    [representation, "#{representation}#{unit}"]
  end
  representations.select{ |(value, string)| value > 0 }.map(&:last).reverse.join(' ')
end
to_s() click to toggle source
# File lib/timing/interval.rb, line 73
def to_s
  representations = UNITS.map.with_index do |unit, i|
    representation = to_representation(unit, false, false)
    [representation, "#{representation.to_i}#{unit}"]
  end
  pair = representations.reverse.detect{ |value,representation| value == value.to_i }
  pair && pair[1] || "#{to_seconds}s"
end

Protected Instance Methods

to_representation(unit, acumulate=false, truncate=true) click to toggle source
# File lib/timing/interval.rb, line 102
def to_representation(unit, acumulate=false, truncate=true)
  value = to_f / CONVERSIONS[unit]
  value = value % MULTIPLIER[unit] if acumulate
  truncate ? value.truncate : value
end