class TimeIntervals::Interval

Attributes

end_at[R]
ended_at[R]
start_at[R]
started_at[R]

Public Class Methods

create(interval) click to toggle source
# File lib/time_intervals/interval.rb, line 19
def self.create(interval)
  new(interval.started_at, interval.ended_at)
end
new(started_at, ended_at) click to toggle source
# File lib/time_intervals/interval.rb, line 23
def initialize(started_at, ended_at)
  raise "Invalid interval" if started_at.nil? || ended_at.nil?

  @started_at = as_seconds(started_at)
  @ended_at = as_seconds(ended_at)

  raise "Invalid interval: #{self}" if @ended_at < @started_at
end

Public Instance Methods

<=>(other) click to toggle source
# File lib/time_intervals/interval.rb, line 65
def <=>(other)
  comparison = started_at <=> other.started_at
  comparison.zero? ? (other.ended_at <=> ended_at) : comparison
end
==(other) click to toggle source
# File lib/time_intervals/interval.rb, line 70
def ==(other)
  other.class == self.class && other.state == state
end
Also aliased as: eql?
after?(other) click to toggle source
# File lib/time_intervals/interval.rb, line 36
def after?(other)
  other.ended_at <= started_at
end
before?(other) click to toggle source
# File lib/time_intervals/interval.rb, line 40
def before?(other)
  ended_at <= other.started_at
end
disjoint?(other) click to toggle source
# File lib/time_intervals/interval.rb, line 44
def disjoint?(other)
  before?(other) || after?(other)
end
eql?(other)
Alias for: ==
hash() click to toggle source
# File lib/time_intervals/interval.rb, line 75
def hash
  state.hash
end
include?(time) click to toggle source
# File lib/time_intervals/interval.rb, line 57
def include?(time)
  started_at <= time && time < ended_at
end
length_in_seconds() click to toggle source
# File lib/time_intervals/interval.rb, line 32
def length_in_seconds
  ended_at - started_at
end
overlap_duration_in_seconds(other) click to toggle source
# File lib/time_intervals/interval.rb, line 52
def overlap_duration_in_seconds(other)
  return 0 if disjoint?(other)
  [other.ended_at, ended_at].min - [other.started_at, started_at].max
end
overlaps?(other) click to toggle source
# File lib/time_intervals/interval.rb, line 48
def overlaps?(other)
  !disjoint?(other)
end
to_s() click to toggle source
# File lib/time_intervals/interval.rb, line 61
def to_s
  "[#{format(started_at)}, #{format(ended_at)}]"
end

Protected Instance Methods

state() click to toggle source
# File lib/time_intervals/interval.rb, line 81
def state
  [started_at, ended_at]
end

Private Instance Methods

as_seconds(time_value) click to toggle source

Round any fractional seconds.

# File lib/time_intervals/interval.rb, line 89
def as_seconds(time_value)
  time_value.round
end
format(time_value) click to toggle source
# File lib/time_intervals/interval.rb, line 93
def format(time_value)
  time_value.strftime("%Y-%m-%d %H:%M:%S")
end