我正在使用icalendar gem解析任意公开Google Calendar ICS导出并在Rails应用程序中显示它们。问题是事件以反向字母顺序显示。我试图弄清楚如何按开始时间(dtstart)按时间顺序对它们进行排序。
控制器:
require 'icalendar'
require 'net/https'
uri = URI('https://calendar.google.com/calendar/ical/7d9i7je5o16ec6cje702gvlih0hqa9um%40import.calendar.google.com/public/basic.ics')
# above is an example calendar of Argentinian holidays
# the actual calendar would theoretically have hour/minute start/end times
calendar = Net::HTTP.get(uri)
cals = Icalendar::Calendar.parse(calendar)
cal = cals.first
@holidays = cal.events
查看:
<% @holidays.each do |x| %>
<div class="event">
<div class="event-title"><strong><%= x.summary.upcase %></strong></div>
<div class="event-room">Room <%= x.location %><span class="event-time"><%= x.dtstart.strftime('%I:%M%p') + ' to ' + x.dtend.strftime('%I:%M%p') %></span>
</div>
</div>
<% end %>
这导致DOM中的事件以反向字母顺序呈现而不是按时间顺序呈现(最好是通过dtstart)。
不幸的是,sort_by!
中的ICalendar
方法似乎未定义。
答案 0 :(得分:0)
刚想出来了。像这样重做控制器:
require 'icalendar'
require 'net/http'
uri = URI('https://calendar.google.com/calendar/ical/7d9i7je5o16ec6cje702gvlih0hqa9um%40import.calendar.google.com/public/basic.ics')
calendar = Net::HTTP.get(uri)
cals = Icalendar::Calendar.parse(calendar)
cal = cals.first
all_events = cal.events
@sorted_events = all_events.sort! { |a,b| a.dtstart <=> b.dtstart }
然后在您的视图中使用@sorted_events而不是@holidays:
<% @sorted_events.each do |x| %>
<div class="event">
<div class="event-title"><strong><%= x.summary.upcase %></strong></div>
<div class="event-room">Room <%= x.location %><span class="event-time"><%= x.dtstart.strftime('%I:%M%p') + ' to ' + x.dtend.strftime('%I:%M%p') %></span>
</div>
</div>
<% end %>
这应该可以解决问题。 .sort!
方法在irb
中无效。