summaryrefslogtreecommitdiff
path: root/app/models/occurrence.rb
blob: 3baf4474a527d1b769570485ae7074adcb068c3f (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
# TODO Make a gem out of the c wrapper
require 'chaos_calendar'

class Occurrence < ApplicationRecord
  
  # Associations
  
  belongs_to :node
  belongs_to :event
  
  # Class Methods
  
  def self.find_in_range start_time, end_time
    includes(:node)
      .where("start_time > ? AND end_time < ?", start_time, end_time)
      .order("start_time")
  end

  def self.find_next
    includes(:node)
      .where("start_time > ?", Time.now)
      .limit(1)
  end

  # Deletes all Occurrences which belong to the given event. Afterwards a few
  # variables are set to save repetitive queries. The occurrences of the given
  # event are then calculated and created.
  def self.generate event
    self.where(:event_id => event.id).delete_all
    
    node        = event.node
    duration    = (event.end_time - event.start_time)
    occurrences = self.generate_dates(event)
    
    occurrences.each do |occurrence|
      self.create(
        :start_time => occurrence,
        :end_time   => (occurrence + duration),
        :node_id    => node.id,
        :event_id   => event.id
      )
    end
  end
  
  # Calculates the start_time of all occurrences for a given event if a proper
  # RRule is provided. An ArgumentError is thrown from within the libical
  # wrapper if the RRule is malformed. If the rrule attribute of an event is
  # nil, it simply returns the event start_time as only occurrence.
  # Return value is always an array of Time objects.
  def self.generate_dates event
    if event.rrule && !event.rrule.empty?
      ChaosCalendar::occurrences( 
        event.start_time, 
        (Time.now + 5.years), 
        event.rrule
      )
    else
      [event.start_time]
    end
      
  end
  
  
  # Instance Methods
  
  def summary
    node.head.title
  end
  
end