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
}
REGEXP =
/^([\d\.]+)([smhdw])$/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seconds) ⇒ Interval

Returns a new instance of Interval.

Raises:

  • (ArgumentError)


22
23
24
25
# File 'lib/timing/interval.rb', line 22

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



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

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

.parse(expression) ⇒ Object



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

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



39
40
41
42
43
# File 'lib/timing/interval.rb', line 39

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



45
46
47
# File 'lib/timing/interval.rb', line 45

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

#inspectObject



56
57
58
# File 'lib/timing/interval.rb', line 56

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

#to_sObject



49
50
51
52
53
54
# File 'lib/timing/interval.rb', line 49

def to_s
  integer = CONVERSIONS.map { |u,f| [to_f / f, "#{to_i / f}#{u}"] }
                       .sort_by { |v,t| v }
                       .detect { |v,t| v == v.to_i }
  integer ? integer[1] : "#{to_seconds}s"
end