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) ⇒ Event

Creates a new Event. Accepts a valid Calendar object.



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/gcal4ruby/event.rb', line 182

def initialize(calendar)
  if not calendar.editable
    raise CalendarNotEditable
  end
  super()
  @xml = EVENT_XML
  @calendar = calendar
  @title = nil
  @content = nil
  @start = nil
  @end = nil
  @where = nil
  @transparency = "http://schemas.google.com/g/2005#event.opaque"
  @status = "http://schemas.google.com/g/2005#event.confirmed"
  @attendees = []
  @reminder = nil
  @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

#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



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

def edited
  @edited
end

#endObject

The event end time



73
74
75
# File 'lib/gcal4ruby/event.rb', line 73

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



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

def published
  @published
end

#reminderObject

The reminder settings for the event, returned as a hash



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

def reminder
  @reminder
end

#startObject

The event start time



71
72
73
# File 'lib/gcal4ruby/event.rb', line 71

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



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

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



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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/gcal4ruby/event.rb', line 372

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
    es = calendar.service.send_get("http://www.google.com/calendar/feeds/#{calendar.id}/private/full")
    REXML::Document.new(es.read_body).root.elements.each("entry"){}.map do |entry|
      puts "element  = "+entry.name if calendar.service.debug
      id = ''
      entry.elements.each("id") {|v| id = v.text}
      puts "id = #{id}" if calendar.service.debug
      if id == query
        entry.attributes["xmlns:gCal"] = "http://schemas.google.com/gCal/2005"
        entry.attributes["xmlns:gd"] = "http://schemas.google.com/g/2005"
        entry.attributes["xmlns"] = "http://www.w3.org/2005/Atom"
        event = Event.new(calendar)
        event.load("<?xml version='1.0' encoding='UTF-8'?>#{entry.to_s}")
        return event
      end
    end
  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
        query_string += "&start-min=#{range[:start].xmlschema}&start-max=#{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("http://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|
      entry.attributes["xmlns:gCal"] = "http://schemas.google.com/gCal/2005"
      entry.attributes["xmlns:gd"] = "http://schemas.google.com/g/2005"
      entry.attributes["xmlns"] = "http://www.w3.org/2005/Atom"
      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



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

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



107
108
109
110
111
112
113
# File 'lib/gcal4ruby/event.rb', line 107

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



127
128
129
130
131
132
# File 'lib/gcal4ruby/event.rb', line 127

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.



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/gcal4ruby/event.rb', line 159

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)


444
445
446
# File 'lib/gcal4ruby/event.rb', line 444

def exists?
  return @exists
end

#load(string) ⇒ Object

Loads the event info from an XML string.



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
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/gcal4ruby/event.rb', line 282

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 = ele.text
         when 'published'
            @published = ele.text
         when 'edited'
            @edited = 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
          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.confirmed"
              @status = :cancelled
          end
        when "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
        end      
    end
end

#recurrenceObject

Returns the current event’s Recurrence information



95
96
97
# File 'lib/gcal4ruby/event.rb', line 95

def recurrence
  @recurrence
end

#recurrence=(r) ⇒ Object

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



117
118
119
120
121
122
123
124
# File 'lib/gcal4ruby/event.rb', line 117

def recurrence=(r)
  if r.is_a?(Recurrence)
    r.event = self
    @recurrence = r
  else
    return false
  end
end

#reloadObject

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



348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/gcal4ruby/event.rb', line 348

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.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/gcal4ruby/event.rb', line 203

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.



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
# File 'lib/gcal4ruby/event.rb', line 224

def to_xml()
  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 = @recurrence.to_s
        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
    end
  end        
  if not @attendees.empty?
    @attendees.each do |a|
      xml.root.add_element("gd:who", {"email" => a[:email], "valueString" => a[:name], "rel" => "http://schemas.google.com/g/2005#event.attendee"})
    end
  end
  xml.to_s
end