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)


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

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



38
39
40
# File 'lib/timing/interval.rb', line 38

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

.parse(expression) ⇒ Object



32
33
34
35
36
# File 'lib/timing/interval.rb', line 32

def self.parse(expression)
  match = REGEXP.match expression.strip
  raise "Invalid interval expression #{expression}" unless match
  new match.captures[0].to_f * CONVERSIONS[match.captures[1].to_sym]
end

Instance Method Details

#begin_of(time) ⇒ Object



59
60
61
62
63
# File 'lib/timing/interval.rb', line 59

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



65
66
67
# File 'lib/timing/interval.rb', line 65

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

#inspectObject



92
93
94
# File 'lib/timing/interval.rb', line 92

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

#to_human(options = {}) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/timing/interval.rb', line 78

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



69
70
71
72
73
74
75
76
# File 'lib/timing/interval.rb', line 69

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