Class: Tod::Shift

Inherits:
Object
  • Object
show all
Defined in:
lib/tod/shift.rb

Overview

Shift is a range-like class that handles wrapping around midnight. For example, the Shift of 2300 to 0200 would include 0100.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(beginning, ending, exclude_end = false) ⇒ Shift

Returns a new instance of Shift.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/tod/shift.rb', line 8

def initialize(beginning, ending, exclude_end=false)
  raise ArgumentError, "beginning can not be nil" unless beginning
  raise ArgumentError, "ending can not be nil" unless ending
  unless [true, false].include? exclude_end
    raise ArgumentError, "exclude_end must be true or false"
  end

  @beginning = beginning
  @ending = ending
  @exclude_end = exclude_end

  normalized_ending = ending.to_i
  normalized_ending += TimeOfDay::NUM_SECONDS_IN_DAY if normalized_ending < beginning.to_i

  @range = Range.new(beginning.to_i, normalized_ending, @exclude_end)

  freeze # Shift instances are value objects
end

Instance Attribute Details

#beginningObject (readonly)

Returns the value of attribute beginning.



6
7
8
# File 'lib/tod/shift.rb', line 6

def beginning
  @beginning
end

#endingObject (readonly)

Returns the value of attribute ending.



6
7
8
# File 'lib/tod/shift.rb', line 6

def ending
  @ending
end

#rangeObject (readonly)

Returns the value of attribute range.



6
7
8
# File 'lib/tod/shift.rb', line 6

def range
  @range
end

Instance Method Details

#contains?(shift) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/tod/shift.rb', line 41

def contains?(shift)
  self.include?(shift.beginning) && self.include?(shift.ending)
end

#durationObject

Return shift duration in seconds. if ending is lower than beginning this method will calculate the duration as the ending time is from the following day



47
48
49
# File 'lib/tod/shift.rb', line 47

def duration
  @range.last - @range.first
end

#exclude_end?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/tod/shift.rb', line 51

def exclude_end?
  @exclude_end
end

#include?(tod) ⇒ Boolean

Returns true if the time of day is inside the shift, false otherwise.

Returns:

  • (Boolean)


28
29
30
31
32
# File 'lib/tod/shift.rb', line 28

def include?(tod)
  second = tod.to_i
  second += TimeOfDay::NUM_SECONDS_IN_DAY if second < @range.first
  @range.cover?(second)
end

#overlaps?(other) ⇒ Boolean

Returns true if ranges overlap, false otherwise.

Returns:

  • (Boolean)


35
36
37
38
39
# File 'lib/tod/shift.rb', line 35

def overlaps?(other)
  a, b = [self, other].map(&:range).sort_by(&:first)
  op = a.exclude_end? ? :> : :>=
  a.last.send(op, b.first)
end