iCalendarをRubyのhashに読み込む

例えば作業記録とかGoogle Calendarに登録した内容からデータを抽出して作業実績報告などのレポートを作成するためにGoogle CalendarからエクスポートしたiCalendarをRubyのhashに読み込むスクリプトを書いた。

#!/usr/bin/ruby

require 'pp'

hash_stack = []
hash_key_stack = []
current_hash = {}
while line = gets
  colon_index = line.index(":")
  key = line.slice(0, colon_index)
  value = line.slice(colon_index + 1, line.length - colon_index - 3)
  if key == "BEGIN"
    hash_stack.push current_hash
    hash_key_stack.push value
    current_hash = {}
    next
  elsif key == "END"
    new_hash = current_hash
    new_hash_key = hash_key_stack.pop
    current_hash = hash_stack.pop
    current_value = current_hash[new_hash_key]
    if current_value.nil?
      current_hash[new_hash_key] = new_hash
    elsif current_value.instance_of?(Array) 
      current_value.push new_hash
    else
      current_hash[new_hash_key] = [current_value, new_hash]
    end
    next
  end
  current_hash[key] = value
end
pp current_hash

このスクリプトは標準入力から読み込むようになっている。

> ical_to.rb < google_calendar.ics

とりあえずここまでできたら後は適当な形式に変換したりレポートデータをCSVで出力したりできると思う。