summaryrefslogtreecommitdiff
path: root/lib/sublab_calendar/calendar.rb
blob: 0f95816161dc6d8ffd55936618182a8946346741 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
module SublabCalendar

  class Calendar

    attr_reader :calendar

    PERIODS = {
      future: ->(ev) { ev.dtstart >= DateTime.now },
      past:   ->(ev) { ev.dtstart < DateTime.now },
      this_month: ->(ev) {
        ev.dtstart >= DateTime.now.beginning_of_month &&
        ev.dtstart <  DateTime.now.end_of_month
      }
    }

    def initialize(ical)
      @calendar = Icalendar.parse(ical).first
    end

    def self.load(url=URL)
      request = HTTPI::Request.new
      request.url = URL
      request.auth.digest(USER, PASS)
      request.auth.ssl.verify_mode = :none
      response = HTTPI.get(request)

      ical = response.body
      new(ical)
    end

    def events
      calendar.events.map(&method(:readable))
    end

    PERIODS.each do |name, selector|
      define_method "#{name}_events" do       # def future_events
        calendar.events.                      #   calendar.events.
          select(&selector).                  #     select(&PERIODS[:future]).
          map(&method(:readable))             #     map(&method(:readable))
      end                                     # end
    end

    def recurring
      events.select(&:recurring?)
    end

    def non_recurring
      events.reject(&:recurring?)
    end

    def all_day
      events.select(&:all_day?)
    end

    def next(count=1)
      future.take(count)
    end

    def readable(event)
      SublabCalendar::Event.new(event)
    end

    def everything_this_month
      normal = events.
                select(&PERIODS[:this_month]).
                reject(&:recurring?).
                map(&method(:readable)).
                flatten

      occs = recurring.map(&:occurrences_this_month).flatten

      EventList.new(normal + occs)
    end

  end

end