Skip to content

Instantly share code, notes, and snippets.

@jswelker
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jswelker/04997f378d9bc02311d2 to your computer and use it in GitHub Desktop.
Save jswelker/04997f378d9bc02311d2 to your computer and use it in GitHub Desktop.
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