2016-09-21 46 views
0

我正在使用icalendar gem解析任意公共Google Calendar ICS導出並將它們顯示在Rails應用程序中。問題是這些事件是以反向字母順序顯示的。我試圖找出如何按開始時間(dtstart)按時間順序排序它們。Ruby/Rails:如何通過dtstart對icalendar文件數據進行排序?

控制器:

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 %> 

這導致在相反的字母順序,而不是按時間順序(優選通過DTSTART)的DOM渲染事件。

不幸的是,ICalendar中的sort_by!方法似乎未定義。

回答

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中不起作用。

相關問題