Class: Timing::Interval

Inherits:
TransparentProxy
  • Object
show all
Defined in:
lib/timing/interval.rb

Constant Summary collapse

UNITS_NAMES =
{
  s: :seconds,
  m: :minutes,
  h: :hours,
  d: :days,
  w: :weeks
}
CONVERSIONS =
{
  s: 1,
  m: 60,
  h: 60 * 60,
  d: 60 * 60 * 24,
  w: 60 * 60 * 24 * 7
}
MULTIPLIER =
{
  s: 60,
  m: 60,
  h: 24,
  d: 7,
  w: 1
}
UNITS =
UNITS_NAMES.map(&:first)
REGEXP =
/^([\d\.]+)([smhdw])$/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seconds) ⇒ Interval

Returns a new instance of Interval.

Raises:

  • (ArgumentError)


46
47
48
49
# 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

Class Method Details

.between(time_1, time_2) ⇒ Object



42
43
44
# File 'lib/timing/interval.rb', line 42

def self.between(time_1, time_2)
  new (time_1 - time_2).round
end

.parse(expression) ⇒ Object



32
33
34
35
36
37
38
39
40
# 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

Instance Method Details

#begin_of(time) ⇒ Object



63
64
65
66
67
# 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) ⇒ Object



69
70
71
# File 'lib/timing/interval.rb', line 69

def end_of(time)
  begin_of(time) + self - 1
end

#inspectObject



96
97
98
# File 'lib/timing/interval.rb', line 96

def inspect
  "#{to_s} (#{to_seconds})"
end

#to_human(options = {}) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
# 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_sObject



73
74
75
76
77
78
79
80
# 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