2012-09-17 51 views
2

我在項目中添加了導入日曆(ics文件)的功能。代碼是這樣的:Ror:導入ics文件

events = ICS::Event.file(File.open(ics_temp_file)) 
    events.each do |event| 
    if event.summary and event.started_on and event.description 
     Event.create(:description => event.description == '\n' ? nil : event.description, 
        :organization_id => @organization.id, 
        :user_id => current_user.id, 
        :event_type => Event::OTHER, 
        :date_time => event.started_on, 
        :title => event.summary, 
        :active => true) 
    else 
     logger.warn("***Error*** Importing ics (bad event)") 
    end 
    end 

正如我們所看到的,我使用的是寶石。我在幾個月前研究過它,它看起來像是ics文件的最佳選擇,即提取ics文件的事件。 這種寶石可以提取這樣的活動:

BEGIN:VEVENT 
something here 
END:VEVENT. 

的問題如下;一些用戶試圖導入日曆(我不知道他們用什麼工具來創建日曆),但事件是這樣的:

BEGIN:VFREEBUSY 
something here 
END:VFREEBUSY. 

所以cuestion是,你知道一個更好的選擇解析ICS文件?也許可以提取所有類型的事件,並且可以執行諸如 events.map(&:vevents)或events.map(&:vfreebusy)。你有什麼想法來解決這個問題嗎?謝謝!

編輯:對不起,我忘了提及,這個寶石已知屬性的列表是這

TRANSP 
    DTEND 
    UID 
    DTSTAMP 
    LOCATION 
    DESCRIPTION 
    URL 
    STATUS 
    SEQUENCE 
    SUMMARY 
    DTSTART 
    CREATED 
# For the alarm… 
    # BEGIN:VALARM (ignored) 
    X-WR-ALARMUID 
    TRIGGER 
    ATTACH 
    ACTION 
    # END:VALARM (ignored) 

因此很容易明白爲什麼這個寶石是不是提取各種活動。

+0

艾姆......我認爲在你的文章中有一個錯字...或者我還沒有足夠的咖啡:「這裏的問題是,這個寶石可以提取這樣的事件:」然後「問題是以下;一些用戶試圖導入日曆(我不知道他們用什麼工具創建日曆),但事件是這樣的:「 – Atastor

回答

2

事實上,自上次我使用該功能以來,寶石icalendar的功能已經得到了改進。現在我試過了:

require 'icalendar' 

ics_file = File.open('../Descargas/basic.ics') # or whatever is the path to your calendar 
cals = Icalendar.parse(ics_file) 

cal = cals.first # you can have many calendars on a single ics file 
events = cal.events + cal.freebusys + cal.todos + cal.journals 

events.each do |event| 
    if event.respond_to?('summary') and event.summary and event.respond_to?('dtstart') and event.dtstart # and so on with the attributes you require... 
    Event.create(some attributes in here) 
    end 
end 

真的很好。這個寶石可以很好地解析ics文件。