如何转换Exchange预约数组结构以适配Rails的simple_calendar gem
解决方案
核心实现代码
针对你给出的数据源结构,可通过Ruby的数组遍历和哈希查找快速转换为目标格式:
# 假设原数组为 arr calendar_events = arr.map do |appointment| # 从elems数组中定位start_time对应的哈希 start_time_entry = appointment[:elems].find { |item| item.key?(:start_time) } # 解析时间字符串为Time对象(simple_calendar支持时间对象) start_time = Time.parse(start_time_entry[:start_time][:text]) # 按预期格式包装为数组 [start_time] end
执行后calendar_events的结构就会符合你给出的预期:
[[2023-02-17 08:00:00 +0800], [2023-02-18 02:00:00 +0800]]
补充优化建议
实际使用simple_calendar时,通常需要事件包含开始时间、结束时间、标题等信息才能正常渲染日历,你可以调整转换逻辑生成更实用的事件结构:
calendar_events = arr.map do |appointment| # 提取开始时间 start_time = Time.parse(appointment[:elems].find { |i| i.key?(:start_time) }[:start_time][:text]) # 提取结束时间 end_time = Time.parse(appointment[:elems].find { |i| i.key?(:end_time) }[:end_time][:text]) # 提取忙碌状态作为标题 busy_type = appointment[:elems].find { |i| i.key?(:busy_type) }[:busy_type][:text] # 生成符合simple_calendar要求的事件哈希 { start: start_time, end: end_time, title: busy_type } end
这种结构可以直接传递给simple_calendar的events参数,日历会自动渲染出带时间段和标题的忙碌事件。
注意事项
- 若存在时区问题,可使用
in_time_zone方法转换到指定时区,例如:Time.parse(xxx).in_time_zone('Beijing') - 如果原数组中存在
elems顺序不固定的情况,上述find方法依然能准确找到对应字段,比按索引取值更稳健
内容的提问来源于stack exchange,提问作者Codrin
相关产品推荐
相关产品推荐

