From ef26fecb6a11c8082b3bc67fcc5567c82d2dda03 Mon Sep 17 00:00:00 2001 From: Lars Henrik Mai Date: Wed, 9 Jul 2014 21:37:23 +0200 Subject: use proper delegator for events and recurrences --- sublab_calendar.rb | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/sublab_calendar.rb b/sublab_calendar.rb index 4863759..eab3759 100644 --- a/sublab_calendar.rb +++ b/sublab_calendar.rb @@ -1,7 +1,9 @@ require 'rubygems' require 'bundler/setup' -require 'icalendar' +require 'date' +require 'active_support/core_ext/date_and_time/calculations' +require 'icalendar/recurrence' require 'open-uri' require 'json' @@ -9,10 +11,76 @@ class SublabCalendar URL = "https://sublab.org:5232/calendars/events" - Event = Struct.new(:summary, :start, :end) do + class Event < SimpleDelegator + + BASIC_ATTRIBUTES = [:summary, :dtstart, :dtend] + + def to_h + BASIC_ATTRIBUTES.inject({}) {|hsh, attr| hsh[attr] = send(attr).to_s; hsh } + end + def to_json(*args) to_h.to_json(*args) end + + def to_s + "<#{self.class} #{self.to_h}>" + end + + def inspect + to_s + end + + def recurring? + ! rrule.empty? + end + + def occurrences_this_month + return nil unless recurring? + occurrences_between(*this_month).map {|occ| Occurrence.new(occ, self) } + end + + private + + def this_month + [Date.today.beginning_of_month, Date.today.end_of_month] + end + + end + + class Occurrence < SimpleDelegator + + attr_reader :event + + def initialize(occurrence, event) + @event = event + super(occurrence) + end + + def to_h + { + summary: summary, + start: start_time, + end: end_time + } + end + + def inspect + to_s + end + + def summary + event.summary + end + + def description + event.description + end + + def to_s + "<#{self.class} #{self.to_h}>" + end + end attr_reader :calendar @@ -38,12 +106,16 @@ class SublabCalendar calendar.events.select {|ev| ev.dtstart < DateTime.now}.map(&method(:readable)) end + def recurring + events.select(&:"recurring?") + end + def next(count=1) future.take(count) end def readable(event) - Event.new(event.summary, event.dtstart.to_s, event.dtend.to_s) + Event.new(event) end end -- cgit v1.2.1