Class: GCal4Ruby::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/gcal4ruby/event.rb

Overview

The Event Class represents a remote event in calendar.

Usage

All usages assume a successfully authenticated Service and valid Calendar.

  1. Create a new Event event = Event.new(calendar) event.title = “Soccer Game” event.start = Time.parse(“12-06-2009 at 12:30 PM”) event.end = Time.parse(“12-06-2009 at 1:30 PM”) event.where = “Merry Playfields” event.save

  2. Find an existing Event event = Event.find(cal, “Soccer Game”, => :first)

  3. Find all events containing the search term event = Event.find(cal, “Soccer Game”)

  4. Create a recurring event for every saturday event = Event.new(calendar) event.title = “Baseball Game” event.where = “Municipal Stadium” event.recurrence = Recurrence.new event.recurrence.start = Time.parse(“13-06-2009 at 4:30 PM”) event.recurrence.end = Time.parse(“13-06-2009 at 6:30 PM”) event.recurrence.frequency = => [“SA”] event.save

  5. Create an event with a 15 minute email reminder event = Event.new(calendar) event.title = “Dinner with Kate” event.start = Time.parse(“20-06-2009 at 5 pm”) event.end = Time.parse(“20-06-209 at 8 pm”) event.where = “Luigi’s” event.reminder = => 15, :method => ‘email’ event.save

  6. Create an event with attendees event = Event.new(calendar) event.title = “Dinner with Kate” event.start = Time.parse(“20-06-2009 at 5 pm”) event.end = Time.parse(“20-06-209 at 8 pm”) event.attendees => => “Kate”, :email => “[email protected]” event.save

After an event object has been created or loaded, you can change any of the attributes like you would any other object. Be sure to save the event to write changes to the Google Calendar service.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(calendar, attributes = {}) ⇒ Event

Creates a new Event. Accepts a valid Calendar object and optional attributes hash.



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/gcal4ruby/event.rb', line 214

def initialize(calendar, attributes = {})
  if not calendar.editable
    raise CalendarNotEditable
  end
  super()
  attributes.each do |key, value|
    self.send("#{key}=", value)
  end
  @xml ||= EVENT_XML
  @calendar ||= calendar
  # @transparency ||= "http://schemas.google.com/g/2005#event.opaque"
  # @status ||= "http://schemas.google.com/g/2005#event.confirmed"
  @attendees ||= []
  @all_day ||= false
end

Instance Attribute Details

#all_dayObject

Flag indicating whether it is an all day event



66
67
68
# File 'lib/gcal4ruby/event.rb', line 66

def all_day
  @all_day
end

#clio_idObject

Returns the value of attribute clio_id.



68
69
70
# File 'lib/gcal4ruby/event.rb', line 68

def clio_id
  @clio_id
end

#clio_updated_atObject

Returns the value of attribute clio_updated_at.



69
70
71
# File 'lib/gcal4ruby/event.rb', line 69

def clio_updated_at
  @clio_updated_at
end

#contentObject

The content for the event



56
57
58
# File 'lib/gcal4ruby/event.rb', line 56

def content
  @content
end

#editedObject (readonly)

The date the event was last edited



85
86
87
# File 'lib/gcal4ruby/event.rb', line 85

def edited
  @edited
end

#endObject

The event end time



77
78
79
# File 'lib/gcal4ruby/event.rb', line 77

def end
  @end
end

#idObject

The unique event ID



64
65
66
# File 'lib/gcal4ruby/event.rb', line 64

def id
  @id
end

#publishedObject (readonly)

The date the event was created



81
82
83
# File 'lib/gcal4ruby/event.rb', line 81

def published
  @published
end

#reminderObject

The reminder settings for the event, returned as a hash



79
80
81
# File 'lib/gcal4ruby/event.rb', line 79

def reminder
  @reminder
end

#startObject

The event start time



75
76
77
# File 'lib/gcal4ruby/event.rb', line 75

def start
  @start
end

#statusObject

A flag indicating the status of the event. Values can be :confirmed, :tentative or :cancelled



62
63
64
# File 'lib/gcal4ruby/event.rb', line 62

def status
  @status
end

#titleObject

The event title



54
55
56
# File 'lib/gcal4ruby/event.rb', line 54

def title
  @title
end

#transparencyObject

A flag for whether the event show as :free or :busy



60
61
62
# File 'lib/gcal4ruby/event.rb', line 60

def transparency
  @transparency
end

#updatedObject (readonly)

The date the event was last updated



83
84
85
# File 'lib/gcal4ruby/event.rb', line 83

def updated
  @updated
end

#whereObject

The location of the event



58
59
60
# File 'lib/gcal4ruby/event.rb', line 58

def where
  @where
end

Class Method Details

.find(calendar, query = '', params = {}) ⇒ Object

Finds the event that matches a query term in the event title or description.

‘query’ is a string to perform the search on or an event id.

The params hash can contain the following hash values

  • scope: may be :all or :first, indicating whether to return the first record found or an array of all records that match the query. Default is :all.

  • range: a hash including a :start and :end time to constrain the search by

  • max_results: an integer indicating the number of results to return. Default is 25.

  • sort_order: either ‘ascending’ or ‘descending’.

  • single_events: either ‘true’ to return all recurring events as a single entry, or ‘false’ to return all recurring events as a unique event for each recurrence.

  • ctz: the timezone to return the event times in



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/gcal4ruby/event.rb', line 442

def self.find(calendar, query = '', params = {})
  query_string = ''
  
  begin 
    test = URI.parse(query).scheme
  rescue Exception => e
    test = nil
  end
  
  if test
    puts "id passed, finding event by id" if calendar.service.debug
    puts "id = "+query if calendar.service.debug
    # event_id = query.gsub("/events/","/private/full/") #fix provided by groesser3
    event_id = query
    
    begin
      es = calendar.service.send_get(event_id)
      puts es.inspect if calendar.service.debug
    rescue Exception => e
    end
    if es
      entry = REXML::Document.new(es.read_body).root
      puts 'event found' if calendar.service.debug
      Event.define_xml_namespaces(entry)
      event = Event.new(calendar)
      event.load("<?xml version='1.0' encoding='UTF-8'?>#{entry.to_s}")
      return event
    end
    return nil
  end

  
  #parse params hash for values
  range = params[:range] || nil
  max_results = params[:max_results] || nil
  sort_order = params[:sortorder] || nil
  single_events = params[:singleevents] || nil
  timezone = params[:ctz] || nil
  
  #set up query string
  query_string += "q=#{CGI.escape(query)}" if query
  if range
    if not range.is_a? Hash or (range.size > 0 and (not range[:start].is_a? Time or not range[:end].is_a? Time))
      raise "The date range must be a hash including the :start and :end date values as Times"
    else
      date_range = ''
      if range.size > 0
        #Added via patch from Fabio Inguaggiato
        query_string += "&start-min=#{CGI::escape(range[:start].xmlschema)}&start-max=#{CGI::escape(range[:end].xmlschema)}"
      end
    end
  end
  query_string += "&max-results=#{max_results}" if max_results
  query_string += "&sortorder=#{sort_order}" if sort_order
  query_string += "&ctz=#{timezone.gsub(" ", "_")}" if timezone
  query_string += "&singleevents=#{single_events}" if single_events
  if query_string
    events = calendar.service.send_get("https://www.google.com/calendar/feeds/#{calendar.id}/private/full?"+query_string)
    ret = []
    REXML::Document.new(events.read_body).root.elements.each("entry"){}.map do |entry|
      Event.define_xml_namespaces(entry)
      event = Event.new(calendar)
      event.load("<?xml version='1.0' encoding='UTF-8'?>#{entry.to_s}")
      ret << event
    end
  end
  if params[:scope] == :first
    return ret[0]
  else
    return ret
  end
end

Instance Method Details

#attendeesObject

Returns an array of the current attendees



104
105
106
# File 'lib/gcal4ruby/event.rb', line 104

def attendees
  @attendees
end

#attendees=(a) ⇒ Object

Accepts an array of email address/name pairs for attendees.

[{:name => 'Mike Reich', :email => '[email protected]'}]

The email address is requried, but the name is optional



111
112
113
114
115
116
117
# File 'lib/gcal4ruby/event.rb', line 111

def attendees=(a)
  if a.is_a?(Array)
    @attendees = a
  else
    raise "Attendees must be an Array of email/name hash pairs"
  end
end

#copyObject

Returns a duplicate of the current event as a new Event object



155
156
157
158
159
160
# File 'lib/gcal4ruby/event.rb', line 155

def copy()
  e = Event.new()
  e.load(to_xml)
  e.calendar = @calendar
  return e
end

#deleteObject

Deletes the event from the Google Calendar Service. All values are cleared.



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/gcal4ruby/event.rb', line 191

def delete
    if @exists    
      if @calendar.service.send_delete(@edit_feed, {"If-Match" => @etag})
        @exists = false
        @deleted = true
        @title = nil
        @content = nil
        @id = nil
        @start = nil
        @end = nil
        @transparency = nil
        @status = nil
        @where = nil
        return true
      else
        return false
      end
    else
      return false
    end
end

#exists?Boolean

Returns true if the event exists on the Google Calendar Service.

Returns:

  • (Boolean)


516
517
518
# File 'lib/gcal4ruby/event.rb', line 516

def exists?
  return @exists
end

#load(string) ⇒ Object

Loads the event info from an XML string.



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/gcal4ruby/event.rb', line 336

def load(string)
  @xml = string
  @exists = true
  xml = REXML::Document.new(string)
  @etag = xml.root.attributes['etag']
  xml.root.elements.each(){}.map do |ele|
      case ele.name
         when 'updated'
            @updated = Time.parse ele.text
         when 'published'
            @published = Time.parse ele.text
         when 'edited'
            @edited = Time.parse ele.text
         when 'id'
            @id, @edit_feed = ele.text
         when 'title'
            @title = ele.text
          when 'content'
            @content = ele.text
          when "when"
            @start = Time.parse(ele.attributes['startTime'])
            @end = Time.parse(ele.attributes['endTime'])
            ele.elements.each("gd:reminder") do |r|
              @reminder = {:minutes => r.attributes['minutes'] ? r.attributes['minutes'] : 0, :hours => r.attributes['hours'] ? r.attributes['hours'] : 0, :days => r.attributes['days'] ? r.attributes['days'] : 0, :method => r.attributes['method'] ? r.attributes['method'] : ''}
            end
            
            puts "#{@start.strftime("%Y-%m-%d")} == #{ele.attributes['startTime']} && #{@end.strftime("%Y-%m-%d")} == #{ele.attributes['endTime']}" if @calendar.service.debug
            if @start.strftime("%Y-%m-%d") == ele.attributes['startTime'] && @end.strftime("%Y-%m-%d") == ele.attributes['endTime']
              puts "ALL DAY" if @calendar.service.debug
              @all_day = true
            end
          when "where"
            @where = ele.attributes['valueString']
          when "link"
            if ele.attributes['rel'] == 'edit'
              @edit_feed = ele.attributes['href']
            end
          when "who"
            if ele.attributes['rel'] == "http://schemas.google.com/g/2005#event.attendee"
            n = {}
            ele.attributes.each do |name, value|
                case name
                  when "email"
                    n[:email] = value
                  when "valueString"
                    n[:name] = value
                end
              end                
           @attendees << n
           end
          when "eventStatus"
          case ele.attributes["value"] 
            when "http://schemas.google.com/g/2005#event.confirmed"
             @status =  :confirmed
            when "http://schemas.google.com/g/2005#event.tentative"
              @status = :tentative
            when "http://schemas.google.com/g/2005#event.canceled"
              @status = :cancelled
          end
        when 'recurrence'
          self.recurrence_from_google(ele.text) #Recurrence.new(ele.text)
        when "gd:transparency"
           case ele.attributes["value"]
              when "http://schemas.google.com/g/2005#event.transparent" 
                @transparency = :free
              when "http://schemas.google.com/g/2005#event.opaque"
                @transparency = :busy
            end
        when "extendedProperty"
          case ele.attributes["name"]
          when "http://schemas.goclio.com/g/2010#event" then
            json = ele.attributes["value"]
            json = ActiveSupport::JSON.decode(json)
            @clio_id = json['guid']
            @clio_updated_at = Time.parse json['updated_at']
          end
        end      
    end
end

#recurrenceObject

Returns the current event’s Recurrence information



99
100
101
# File 'lib/gcal4ruby/event.rb', line 99

def recurrence
  @recurrence
end

#recurrence=(r) ⇒ Object

Sets the event’s recurrence information to a Recurrence object. Returns the recurrence if successful, false otherwise



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/gcal4ruby/event.rb', line 121

def recurrence=(r)
  if r.is_a?(RiCal.Event.class)
    @recurrence = r
  elsif r.nil?
    @recurrence = nil
  else
    return false
  end
  if (@recurrence)
    @start = @recurrence.dtstart
    @end = @recurrence.dtend
    if @recurrence.dtstart.is_a?(Date) && @recurrence.dtend.is_a?(Date)
      @all_day = true
    else
      @all_day = false
    end
  end
  @recurrence
end

#recurrence_from_google(rec) ⇒ Object



145
146
147
148
149
150
151
152
# File 'lib/gcal4ruby/event.rb', line 145

def recurrence_from_google(rec)
  rec = "BEGIN:VEVENT\n#{rec}" unless (rec.starts_with? "BEGIN:VEVENT")
  rec = "#{rec}END:VEVENT\n" unless (rec.ends_with? "END:VEVENT\n")
  
  rrule = RiCal.parse_string(rec)
  rrule = [rrule].flatten.first
  self.recurrence = rrule
end

#recurrence_to_googleObject



141
142
143
# File 'lib/gcal4ruby/event.rb', line 141

def recurrence_to_google
  @recurrence.to_s.gsub("BEGIN:VEVENT\n","").gsub("END:VEVENT\n","")
end

#reloadObject

Reloads the event data from the Google Calendar Service. Returns true if successful, false otherwise.



418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/gcal4ruby/event.rb', line 418

def reload
  t = Event.find(@calendar, @id)
  if t
    if load(t.to_xml)
     return true
    else
     return false
    end
  else
    return false
  end
end

#saveObject

If the event does not exist on the Google Calendar service, save creates it. Otherwise updates the existing event data. Returns true on success, false otherwise.



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/gcal4ruby/event.rb', line 232

def save
  if @deleted
    return false
  end
  if @exists 
    ret = @calendar.service.send_put(@edit_feed, to_xml, {'Content-Type' => 'application/atom+xml', "If-Match" => @etag})
  else
    ret = @calendar.service.send_post(@calendar.event_feed, to_xml, {'Content-Type' => 'application/atom+xml'})
  end
  if !@exists
    if load(ret.read_body)
      return true
    else
      raise EventSaveFailed
    end
  end
  reload
  return true
end

#to_xmlObject

Returns an XML representation of the event.



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/gcal4ruby/event.rb', line 253

def to_xml()
  updated_clio_id = false
  xml = REXML::Document.new(@xml)
  xml.root.elements.each(){}.map do |ele|
    case ele.name
    when 'id'
      ele.text = @id
    when "title"
      ele.text = @title
    when "content"
      ele.text = @content
    when "when"
      if not @recurrence
        ele.attributes["startTime"] = @all_day ? @start.strftime("%Y-%m-%d") : @start.xmlschema
        ele.attributes["endTime"] = @all_day ? @end.strftime("%Y-%m-%d") : @end.xmlschema
        set_reminder(ele)
      else
        if not @reminder
          xml.root.delete_element("/entry/gd:when")
          xml.root.add_element("gd:recurrence").text = self.recurrence_to_google
        else
          ele.delete_attribute('startTime')
          ele.delete_attribute('endTime')
          set_reminder(ele)  
        end
      end
    when "eventStatus"
      ele.attributes["value"] = case @status
        when :confirmed
          "http://schemas.google.com/g/2005#event.confirmed"
        when :tentative
          "http://schemas.google.com/g/2005#event.tentative"
        when :cancelled
          "http://schemas.google.com/g/2005#event.canceled"
        else
          "http://schemas.google.com/g/2005#event.confirmed"
      end
    when "transparency"
      ele.attributes["value"] = case @transparency
          when :free
            "http://schemas.google.com/g/2005#event.transparent"
          when :busy
            "http://schemas.google.com/g/2005#event.opaque"
          else
            "http://schemas.google.com/g/2005#event.opaque"
        end
    when "where"
      ele.attributes["valueString"] = @where
    when "recurrence"
      puts 'recurrence element found' if @calendar.service.debug
      if @recurrence
        puts 'setting recurrence' if @calendar.service.debug
        ele.text = self.recurrence_to_google
      else
        puts 'no recurrence, adding when' if @calendar.service.debug
        w = xml.root.add_element("gd:when")
        xml.root.delete_element("/entry/gd:recurrence")
        w.attributes["startTime"] = @all_day ? @start.strftime("%Y-%m-%d") : @start.xmlschema
        w.attributes["endTime"] = @all_day ? @end.strftime("%Y-%m-%d") : @end.xmlschema
        set_reminder(w)
      end
    when "extendedProperty"
      ele.attributes["value"] = case ele.attributes["name"]
      when "http://schemas.goclio.com/g/2010#event" then
        updated_clio_id = true
        { :guid => @clio_id, :updated_at => @clio_updated_at }.to_json
      end
    end
  end        
  if not @attendees.empty?
    @attendees.each do |a|
      a = xml.root.add_element("gd:who", {"email" => a[:email], "valueString" => a[:name], "rel" => "http://schemas.google.com/g/2005#event.attendee"})
      a.add_element("gd:attendeeStatus", {"value" => "http://schemas.google.com/g/2005#event.accepted"})
    end
  end
  unless updated_clio_id
    value = { :guid => @clio_id, :updated_at => @clio_updated_at }.to_json
    xml.root.add_element("gd:extendedProperty", {"name" => "http://schemas.goclio.com/g/2010#event", "value"=> value })
  end
  xml.to_s
end