Using Ruby To Create iCal Events

Calendars can be so tedious, so I hacked mine.

Anytime we have a new season begin, or I start a new running training plan, I have a bunch of events that need to be created. Usually you just sit down and take the half hour (or whatever) to bang all the events out. You can copy and paste events in iCal from day to day, which helps. But it still sucks.

So I finally sat down and figured out how to script it.

Gemfile:

# A sample Gemfile
source "https://rubygems.org"
ruby '2.2.2'

gem "icalendar"

Script (make_events.rb):

require "rubygems"
require "bundler"
require "csv"
require "date"
Bundler.require

### Create iCal ics file with multiple events
class EventCreator
  attr_reader :cal

  def initialize
    @cal = Icalendar::Calendar.new
    make_events
  end

  def make_events
    dt = DateTime.civil(2015, 6, 6, 0, 7, 0)
    3.times do |i|
      event          = Icalendar::Event.new
      event.dtstart  = dt + i
      event.duration = "P30M"
      event.summary  = "Test Event #{i}!"
      @cal.add_event(event)
    end
  end

  def to_ics
    File.open("scripted.ics", "w") { |f| f.write @cal.to_ical }
  end
end

if __FILE__ == $0
  calendar = EventCreator.new
  calendar.to_ics
end

So all you have to do from the command line, after you’ve run bundle install is ruby make_events.rb. It will create a single ics file that you can import into iCal. When you open the file you will be asked what calendar you want to import the events into.

Note: The gem does not appear to support “full day” events. That’s ok. Next up for me is to create a running training plan given a CSV file. I’ll post that next.

4 Comments

Filed under programming, ruby