Class: Reservation::Schedule::Weekly

Inherits:
Object
  • Object
show all
Defined in:
lib/reservation/schedule.rb

Overview

Weekly defines a set of intervals that recur weekly

This class maintains an array of intervals for each weekday

This class will never match multi-day events, as it assumes each event starts and ends within the same day

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ Weekly

pattern is an array of the form

[ { "day" => "wed", "start" => "0930", "finish" => "10:30"},
  { "day" => "wed", "start" => "18",   "finish" => "20"   },
  { "day" => "tue", "start" => "7",    "finish" => "8h30" }  ]

see HourMinute#parse for how “start” and “finish” values are read



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/reservation/schedule.rb', line 141

def initialize pattern
  self.wdays = (0..6).map { |i| Daily.new(i) }

  pattern.each { |interval_spec|
    wday   = DAY_MAP[interval_spec["day"]]
    raise "unrecognised day #{spec["day"].inspect} in #{pattern.inspect}" if wday.nil?

    start  = HourMinute.parse interval_spec["start"]
    finish = HourMinute.parse interval_spec["finish"]
    wdays[wday].add Interval.new(start, finish)
  }
end

Instance Attribute Details

#wdaysObject

wdays is a 7-element array of Daily instances

the zeroth element corresponds to Sunday, because Time#wday behaves that way.



131
132
133
# File 'lib/reservation/schedule.rb', line 131

def wdays
  @wdays
end

Instance Method Details

#filter(events) ⇒ Object

return a new list including only those events in the given list that match this weekly schedule



182
183
184
# File 'lib/reservation/schedule.rb', line 182

def filter events
  events.select { |e| matches? e }
end

#generate(from, upto) ⇒ Object

generate a set of Events according to this Weekly schedule, starting on #from at the earliest, ending on #upto at the latest.

Note: #upto is inclusive, this will generate events on #upto, if the schedule allows



170
171
172
173
174
175
176
# File 'lib/reservation/schedule.rb', line 170

def generate from, upto
  events = []
  from.upto(upto).map { |date|
    wdays.each { |day| day.generate date, events }
  }
  events
end

#matches?(event) ⇒ Boolean

true if there exists a Daily corresponding to this event’s weekday, with an Interval corresponding to this event’s start and finish times; false otherwise



158
159
160
161
# File 'lib/reservation/schedule.rb', line 158

def matches? event
  return false if event.start.day != event.finish.day
  wdays[event.start.wday].matches? event
end

#to_sObject



186
187
188
# File 'lib/reservation/schedule.rb', line 186

def to_s
  wdays.map(&:to_s).join "\n"
end