Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Calendar iCal parser demo for Rails
#requires the following gems: net/http, chronic, icalendar, ice_cube
#for ice_cube, I had to use a branch that had not yet been pulled into master.
#In gemfile: gem 'ice_cube', :git => 'https://github.com/spra85/ice_cube.git'
class LibraryHoursCalendarBuilder
def get_hours
@calendars = LibraryHoursCalendar.all.order( "sort_order ASC" )
@calendars.each do |calendar|
#For each calendar, get the ical file from Google and parse it
require 'net/http'
ical = Net::HTTP.get( URI( calendar.ical_url ) )
ical_contents = Icalendar.parse( ical )
ical_calendar = ical_contents.first
ical_calendar.events.each do |event|
schedule = IceCube::Schedule.new( event.dtstart.to_date )
if event.rrule[0].blank?
occurrences = [ event.dtstart ]
else
schedule.add_recurrence_rule( IceCube::Rule.from_ical( event.rrule[0].value_ical ) )
if !event.exdate.blank?
event.exdate.each do |exdate|
schedule.add_exception_time( exdate.to_time )
end
end
occurrences = schedule.occurrences( Time.now + 1.year )
end
#For all the occurrences of a calendar event (as defined in the RRULE recurrence rule),
#create/update an entry in the database.
occurrences.each do |occurrence|
#First look to see if this date already exists for the calendar and try to update it
calendar_entry = LibraryHoursCalendarEntry.find_by( :entry_date => occurrence.to_date, :calendar_id => calendar.id)
#If this date doesn't exist, create a new entry
if calendar_entry.blank?
calendar_entry = LibraryHoursCalendarEntry.new
calendar_entry.entry_date = occurrence.to_date
calendar_entry.calendar_id = calendar.id
end
#Update the entry if it has changed or if this is a new record
if calendar_entry.entry_content != event.summary or calendar_entry.new_record?
calendar_entry.entry_content = event.summary.to_s
entry_times = event.summary.split( "to" )
if entry_times.length > 1 and !event.summary.downcase.include? "closed"
calendar_entry.open_time = Chronic.parse( occurrence.to_date.to_s + " " + entry_times[0] )
calendar_entry.close_time = Chronic.parse( occurrence.to_date.to_s + " " + entry_times[1] )
else
calendar_entry.open_time = nil
calendar_entry.close_time = nil
end
#Save the entry
calendar_entry.save
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.