Permalink
Browse files

add gcalendar for holidays

  • Loading branch information...
1 parent 41c02cc commit c00fd23adf05fe3d935175e5f362a9a8c62873e2 @melborne committed Dec 9, 2010
Showing with 84 additions and 0 deletions.
  1. +68 −0 lib/gcalendar.rb
  2. +16 −0 test/tc_gcalendar.rb
View
@@ -0,0 +1,68 @@
+#!/usr/bin/env ruby
+#-*-encoding: utf-8-*-
+# Google Calendar Data API for retrieving holiday data
+require "open-uri"
+require "nokogiri"
+require "cgi"
+
+class GCalendar
+ def initialize(year, month=nil)
+ @year, @month = year, month
+ end
+
+ def holidays(country=:ja_ja)
+ parse_xml_to_hash get_holidays(country)
+ end
+
+ private
+ def get_holidays(country)
+ open URL(country) + PARAM(*build_date_range)
+ rescue => e
+ STDERR.puts "Failed to retrieve Holiday data by Google Calendar Data API. #{e}"
+ end
+
+ def URL(country)
+ "http://www.google.com/calendar/feeds/" +
+ CGI.escape("#{COUNTRY_ID(country)}") + "/public/full-noattendees?"
+ end
+
+ def COUNTRY_ID(country)
+ base1 = "@holiday.calendar.google.com"
+ base2 = "#holiday@group.v.calendar.google.com"
+ {
+ ja: "japanese#{base1}",
+ us: "usa__en#{base1}",
+ au: "australian__en#{base1}",
+ ja_ja: "ja.japanese#{base2}",
+ cn: "en.china#{base2}",
+ fr: "en.french#{base2}",
+ de: "en.german#{base2}",
+ it: "en.italian#{base2}",
+ kr: "en.south_korea#{base2}",
+ tw: "en.taiwan#{base2}",
+ gb: "en.uk#{base2}"
+ }[country]
+ end
+
+ def PARAM(sd, ed)
+ "start-min=#{sd}&start-max=#{ed}"
+ end
+
+ def build_date_range
+ st, ed = @month ? [format("%02d", @month)] * 2 : ["01", "12"]
+ return "#{@year}-#{st}-01", "#{@year}-#{ed}-31"
+ end
+
+ def parse_xml_to_hash(xml)
+ data = Nokogiri::HTML(xml)
+ h = {}
+ data.css("entry").each do |node|
+ date = node.css("gd", "when").attr("starttime").value
+ h[Time.parse date] = node.css("title").text
+ end
+ h
+ end
+end
+
+g = GCalendar.new(2010, 9)
+g.holidays
View
@@ -0,0 +1,16 @@
+require "test/unit"
+
+require_relative "../lib/gcalendar"
+
+class TestLibGcalendar < Test::Unit::TestCase
+ def test_holidays_for_a_month
+ gc = GCalendar.new(2010, 12)
+ assert_equal(23, gc.holidays.keys[0].day)
+ end
+
+ def test_holidays_for_a_year
+ gc = GCalendar.new(2010)
+ puts holidays_ja = gc.holidays.map { |k, v| "#{k.strftime("%m/%d")} => #{v}" }
+ puts holidays_us = gc.holidays(:us).map { |k, v| "#{k.strftime("%m/%d")} => #{v}" }
+ end
+end

0 comments on commit c00fd23

Please sign in to comment.