Exchange calendar to Ruby object. Please comment the code

I have written this peace of code to extract data from Exchange calendar
folder and fill it into ruby object, so it can be accesed later like:
puts calendar.vevent.dtstart
puts calendar.vevent.dtend
puts calendar.vevent.attendee
puts calendar.vevent.description

Since I am still lerning Ruby I am interested what do you old Rubyists
think of the code. Could it be done any better.

Translating this to Hash or even XML should be trivial.

by

TheR

#############################################################################

Read message from Exchange calendar folder with IMAP and create object

filled with values from message.

Written by Damjan R. 16.03.2007

#############################################################################
require ‘net/imap’

ExchangeCalendar

def addVar(var, val)
var.gsub!(‘-’,‘_’) # - is not allowed
as variable name
if instance_variable_get(“@#{var}”) == nil # if not already set
instance_variable_set(“@#{var}”, val) # set it
eval(“def #{var}; @#{var}; end”) # define method for
retrive
else # if already defined than it should be array of values
if instance_variable_get(“@#{var}”).class != ‘Array’ # second
value
a = Array.new # create
array
a << instance_variable_get(“@#{var}”) # add old
value to first element
instance_variable_set(“@#{var}”, a) # set
variable to array
else
a = instance_variable_get(“@#{var}”)
end
a << val # add new
element to array
end
end
end

#############################################################################
def msg2calendar(msg)
ar = Array.new
ix = 0
ar[ix] = ExchangeCalendar.new

msg.gsub!("\r\n ",‘’) # Remove line breaks in data
msg.each_line do |l|
l.chomp! # remove whitespace
dc = l.index(‘:’) # Some keywords are delimited
with colon (:slight_smile:
i=if (ds = l.index(‘;’)) == nil # some with semicolon (:wink:
dc
elsif dc==nil
ds
else
ds < dc ? ds : dc
end
key = l[0,i].downcase # get keyword and lowercase it
val = l[i+1,l.length] # get value

if key == 'begin'                   # Create new level if begin
  if val != 'VCALENDAR'             # First level is already

prepared
ix += 1
ar[ix] = ExchangeCalendar.new
ar[ix-1].addVar(val.downcase, ar[ix])
end
elsif key == ‘end’ # Step one level back
ix -= 1
else
ar[ix].addVar(key,val) # add new variable
end
end
ar[0]
end

imap = Net::IMAP.new(‘mail.domain.com’)
imap.login(‘user’, ‘pwd’)
imap.select(‘Public Folders/Any calendar’)
imap.search([“SINCE”, “10-Mar-2007”]).each do |message_id|
calendar = msg2calendar(imap.fetch(message_id,
“BODY[2]”)[0].attr[“BODY[2]”])
puts calendar.vevent.dtstart
puts calendar.vevent.dtend
puts calendar.vevent.attendee
puts calendar.vevent.description
end