Using Ruby To Make iCal Events, Part 2

Earlier I discussed creating calendar events with Ruby to take the pain out of creating a lot of events. I just finished up a script that created 126 events in seconds. Here are the relevant bits (in addition to the earlier post).

Input

My input CSV looks like this (below). It’s Hal Higdon’s Intermediate 1 plan.

Date,Week,Day,Description
6/8/2015,1,MON,Cross
6/9/2015,1,TUE,3 miles
6/10/2015,1,WED,5 miles
6/11/2015,1,THU,3 miles
6/12/2015,1,FRI,Rest
6/13/2015,1,SAT,5 miles (pace)
6/14/2015,1,SUN,8 miles
6/15/2015,2,MON,Cross
6/16/2015,2,TUE,3 miles

I copied the grid at the bottom and pasted it into Excel. I created another tab to handle the ETL. You can highlight a row and paste special (right click shows you this option) to transpose the cells. That allows you to take a row and paste it as a column. Yes, I can Excel pretty good. Excel sucks at regex though, so I let Ruby handle teasing out the meaning of each of the workouts.

The Code

  def read_input(infile)
    CSV.foreach(infile, :headers => true) do |row|
      m, d, y     = row['Date'].split(/\//).map(&:to_i)
      date        = DateTime.civil(y, m, d, 7, 0, 0)
      description = row['Description']
      next if description == "Rest"
      minutes = if description.match(/^\d{1,2}/)
                  description.match(/^\d{1,2}/)[0].to_i * 10
                else
                  30
                end
      event = Icalendar::Event.new
      event.dtstart  = date
      event.duration = "P#{minutes}M"
      event.summary  = description
      event.comment  = "Event created with Ruby script"
      @cal.add_event(event)
    end
  end

It’s not pretty. That method is doing a lot. The event comment isn’t saved either. That’s OK. I still got what I need — a whole lot of events that I didn’t have to type myself, and a script (and process) that I can use moving forward.

Win-win.

Leave a Comment

Filed under programming, ruby