【发布时间】:2014-09-03 17:22:27
【问题描述】:
我正在编写一个约会表格,让用户选择一个日期。然后它将获取日期并对照 Google 日历检查在上午 10:00 到下午 5:00 的 30 分钟时间间隔范围内该日期的可用时间段。
在我的日历类中,我有一个 available_times 方法:
def available_times(appointment_date)
appointment_date_events = calendar.events.select { |event| Date.parse(event.start_time) == appointment_date }
conflicts = appointment_date_events.map { |event| [Time.parse(event.start_time), Time.parse(event.end_time)] }
results = resolve_time_conflicts(conflicts)
end
此方法需要一个日期,并为该日期的每个事件获取 start_time 和 end_time。然后它调用resolve_time_conflicts(conflicts):
def resolve_time_conflicts(conflicts)
start_time = Time.parse('10:00am')
available_times = []
14.times do |interval_multiple|
appointment_time = (start_time + interval_multiple * (30 * 60))
available_times << appointment_time unless conflicts.each{ |conflict| (conflict[0]..conflict[1]).include?(appointment_time)}
end
available_times
end
当我尝试迭代冲突数组时,会引发“无法迭代时间”错误。我试图在冲突数组上调用to_enum,但仍然遇到同样的错误。
我在 SO 上看到的所有其他问题都引用了 step 方法,这似乎不适用于这种情况。
更新:
Thanks @caryswoveland and @fivedigit. I combined both of your answers, which were very helpful for different aspects of my solution:
def available_times(appointment_date)
appointment_date_events = calendar.events.select { |event| Date.parse(event.start_time) == appointment_date }
conflicts = appointment_date_events.map { |event| DateTime.parse(event.start_time)..DateTime.parse(event.end_time) }
results = resolve_time_conflicts(conflicts)
end
def resolve_time_conflicts(conflicts)
date = conflicts.first.first
start_time = DateTime.new(date.year, date.month, date.day, 10, 00).change(offset: date.zone)
available_times = []
14.times do |interval_multiple|
appointment_time = (start_time + ((interval_multiple * 30).minutes))
available_times << appointment_time unless conflicts.any? { |conflict| conflict.cover?(appointment_time)}
end
available_times
end
【问题讨论】:
-
如果您将
conflicts计算为范围数组(Time.parse(event.start_time)..Time.parse(event.end_time))(而不是数组数组),则可以编写...|conflict| conflict.cover?(...。 -
你能举一个
calendar.events元素的例子吗? -
@CarySwoveland - 谢谢,这更有意义!看了我上面的修改后,你还想看 calender.events 的元素吗?
-
仅当您仍然需要知道如何使
appointment_time日期与conflicts日期相同时。
标签: ruby time google-calendar-api