by simon baird

Friday, July 28, 2006

Aw... my first real inject

It's a special moment for any ruby programmer when they create their very first real inject. I don't mean in some sample code but in a real live program. It just happened to me and I'm very proud. :) Here it is:
#!/usr/bin/ruby

require 'uri'
require 'net/http'

LINE_MATCH       = /\/\/DATA\|\|\|/
FIELD_DELIM      = /\|\|\|/
NAME_VALUE_DELIM = /:/

url = 'http://www.jcu.edu.au/app/timetable/?subjectslist=CP1010&campus=Townsville&sem=2&doit=yes'

data = Net::HTTP.get(URI.parse(url)).to_a.grep(LINE_MATCH).map do |line|
  line.strip!.sub!(LINE_MATCH,'').split(FIELD_DELIM).inject({}) do |hash,pair|
    name,val = pair.split(NAME_VALUE_DELIM)
    hash.merge(name.to_sym => val)
  end
end

p data
I'm writing a hack to scrape timetable data from an existing web app and convert it to iCalendar format. I have the ruby iCalendar gem so I think I'm almost done. ...happy dance...

1 comment:

Green Apple Cat said...

Wow! And Miranda thinks I'M a geek.