Recipe: Google Calendar

Dan Croak

A recipe for accessing Google Calendar data from Ruby.


Google Calendar is a great interface for a few people to share management of events. You might have a client that has this need. Neither you nor the client want to spend time or money duplicating an ‘admin interface’ for managing events. You want to focus development time on displaying those events in a custom way.


Google Calendar

For a Google Calendar you own, navigate to the “Calendar Details” page.

Your calendar has an address and can be accessed as XML/RSS, iCalendar, or HTML.

A good example of the Google Calendar embed option is Betahouse’s calendar.


For this recipe, we’ll use the iCalendar format. I tried GET'ing the XML version and parsing it with Nokogiri but found the iCalendar version more manageable.

Copy the “ICAL” button’s value. Save it in a comment in your code for now. Also download it. We’ll use it for our spec:

describe Tour do
  before do
    ics   = File.join(File.dirname(__FILE__), 'local_copy.ics')
    @tour =

  it "should find upcoming gigs" do
    @tour.upcoming_gigs.all? { |gig| gig.dtstart.should > }

Make it go:

require 'open-uri'

class Tour

  attr_accessor :cal

  def initialize(ics = GOOGLE_ICS) = Icalendar.parse(open(ics).read).first
  rescue *HTTP_ERRORS => error

  def upcoming_gigs  { |event| event.dtstart > }.
                sort_by { |event| event.dtstart }

The default behavior uses the remote Google ics file, but we set up a constructor to allow us to easily replace the file in our specs.

The rescue is optional. HTTP_ERRORS is an Array from Suspenders

I use in these circumstances in combination with Hoptoad to be notified if the HTTP calls to a remote service stop working for some reason.

If you wanted to get really fancy, you could have a nightly cron job that downloads a new copy of the .ics file and runs the spec on CI.

Example web app

I happened to be doing this in order to style the calendar nicely in a web app.

Here’s my Sinatra route…

get '/tour' do
  erb :tour, :locals => { :gigs => }

… and the relevant portion of the view:

<% gigs.each do |gig| %>*   <%= gig.dtstart.strftime("%B %d, %Y %I:%M %p") %>
    ["><%= gig.summary %>](<%= gig.location %)

Check out the live example.

Bon appétit!