Ruby/Rails: 如何通过dtstart 对icalendar 文件数据进行排序?

Ruby/Rails: How to sort icalendar file data by dtstart?

我正在使用 icalendar gem 解析任意 public Google 日历 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)。

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

刚刚弄明白了。像这样重做控制器:

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