Class: GCal4Ruby::Event

Inherits:
GData4Ruby::GDataObject
  • 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(service, => cal, :title => “Soccer Game”, :start => Time.parse(“12-06-2009 at 12:30 PM”), :end => Time.parse(“12-06-2009 at 1:30 PM”), :where => “Merry Playfields”) event.save

  2. Find an existing Event by title event = Event.find(service, => “Soccer Game”)

  3. Find an existing Event by ID event = Event.find(service, => event.id)

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

  5. Find all events on a calendar containing the search term event = Event.find(service, “Soccer Game”, => cal.id)

  6. Find events within a date range event = Event.find(service, “Soccer Game”, => Time.parse(“01/01/2010”).utc.xmlschema, ‘start-max’ => Time.parse(“06/01/2010”).utc.xmlschema)

  7. Create a recurring event for every saturday event = Event.new(service) event.title = “Baseball Game” event.calendar = cal event.where = “Municipal Stadium” event.recurrence = Recurrence.new event.recurrence.start_time = Time.parse(“06/20/2009 at 4:30 PM”) event.recurrence.end_time = Time.parse(“06/20/2009 at 6:30 PM”) event.recurrence.frequency = => [“SA”] event.save

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

  9. Create an event with attendees event = Event.new(service) event.calendar = cal event.title = “Dinner with Kate” event.start_time = Time.parse(“06/20/2009 at 5 pm”) event.end_time = Time.parse(“06/20/2009 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.

Constant Summary collapse

EVENT_QUERY_FEED =
"http://www.google.com/calendar/feeds/default/private/full/"
EVENT_XML =
"<entry xmlns='http://www.w3.org/2005/Atom'
    xmlns:gd='http://schemas.google.com/g/2005'>
  <category scheme='http://schemas.google.com/g/2005#kind'
    term='http://schemas.google.com/g/2005#event'></category>
  <title type='text'></title>
  <content type='text'></content>
  <gd:transparency
    value='http://schemas.google.com/g/2005#event.opaque'>
  </gd:transparency>
  <gd:eventStatus
    value='http://schemas.google.com/g/2005#event.confirmed'>
  </gd:eventStatus>
  <gd:where valueString=''></gd:where>
  <gd:when startTime=''
    endTime=''></gd:when>
</entry>"
STATUS =
{:confirmed => "http://schemas.google.com/g/2005#event.confirmed",
:tentative => "http://schemas.google.com/g/2005#event.tentative",
:cancelled => "http://schemas.google.com/g/2005#event.canceled"}
TRANSPARENCY =
{:free => "http://schemas.google.com/g/2005#event.transparent",
:busy => "http://schemas.google.com/g/2005#event.opaque"}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

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



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/gcal4ruby/event.rb', line 122

def initialize(service, attributes = {})
  super(service, attributes)
  @xml = EVENT_XML
  @transparency ||= :busy
  @status ||= :confirmed
  @attendees ||= []
  @all_day ||= false
  @reminder = []
  attributes.each do |key, value|
    self.send("#{key}=", value)
  end
end

Instance Attribute Details

#all_dayObject

Flag indicating whether it is an all day event



113
114
115
# File 'lib/gcal4ruby/event.rb', line 113

def all_day
  @all_day
end

#calendar_idObject (readonly)

Id of the parent calendar



119
120
121
# File 'lib/gcal4ruby/event.rb', line 119

def calendar_id
  @calendar_id
end

#contentObject

The content for the event



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

def content
  @content
end

#editedObject (readonly)

The date the event was last edited



117
118
119
# File 'lib/gcal4ruby/event.rb', line 117

def edited
  @edited
end

#reminderObject

The reminder settings for the event, returned as a hash



115
116
117
# File 'lib/gcal4ruby/event.rb', line 115

def reminder
  @reminder
end

#statusObject

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



111
112
113
# File 'lib/gcal4ruby/event.rb', line 111

def status
  @status
end

#transparencyObject

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



109
110
111
# File 'lib/gcal4ruby/event.rb', line 109

def transparency
  @transparency
end

#whereObject

The location of the event



107
108
109
# File 'lib/gcal4ruby/event.rb', line 107

def where
  @where
end

Class Method Details

.find(service, query, args = {}) ⇒ Object

Finds an Event based on a text query or by an id. Parameters are:

service

A valid Service object to search.

query

either a string containing a text query to search by, or a hash containing an id key with an associated id to find, or a query key containint a text query to search for, or a title key containing a title to search. All searches are case insensitive.

args

a hash containing optional additional query paramters to use. Limit a search to a single calendar by passing the calendar id as => calendar.id. See here and here for a full list of possible values. Example:

=> ‘100’ If an ID is specified, a single instance of the event is returned if found, otherwise false. If a query term or title text is specified, and array of matching results is returned, or an empty array if nothing was found.

Raises:

  • (ArgumentError)


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
# File 'lib/gcal4ruby/event.rb', line 366

def self.find(service, query, args = {})
  raise ArgumentError, 'query must be a hash or string' if not query.is_a? Hash and not query.is_a? String
  if query.is_a? Hash and query[:id]
    id = query[:id]
    puts "id passed, finding event by id" if service.debug
    puts "id = "+id if service.debug
    d = service.send_request(GData4Ruby::Request.new(:get, "http://www.google.com/calendar/feeds/"+id, {"If-Not-Match" => "*"}))
    puts d.inspect if service.debug
    if d
      return get_instance(service, d)
    end
  else
    results = []
    if query.is_a?(Hash)
      args["q"] = query[:query] if query[:query]
      args['title'] = query[:title] if query[:title]
    else
      args["q"] = CGI::escape(query) if query != ''
    end
    if args[:calendar]
      cal = Calendar.find(service, {:id => args[:calendar]})
      args.delete(:calendar)
      ret = service.send_request(GData4Ruby::Request.new(:get, cal.content_uri, nil, nil, args))
      xml = REXML::Document.new(ret.body).root
      xml.elements.each("entry") do |e|
        results << get_instance(service, e)
      end
    else
      service.calendars.each do |cal|
        ret = service.send_request(GData4Ruby::Request.new(:get, cal.content_uri, nil, nil, args))
        xml = REXML::Document.new(ret.body).root
        xml.elements.each("entry") do |e|
          results << get_instance(service, e)
        end
      end
    end
    return results
  end
  return false
end

Instance Method Details

#attendeesObject

Returns an array of the current attendees



149
150
151
# File 'lib/gcal4ruby/event.rb', line 149

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

Raises:

  • (ArgumentError)


168
169
170
171
# File 'lib/gcal4ruby/event.rb', line 168

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

#calendarObject

The event’s parent calendar



288
289
290
291
# File 'lib/gcal4ruby/event.rb', line 288

def calendar 
  @parent_calendar = Calendar.find(service, {:id => @calendar_id}) if not @parent_calendar and @calendar_id
  return @parent_calendar
end

#calendar=(p) ⇒ Object

Sets the event’s calendar

Raises:

  • (ArgumentError)


294
295
296
297
# File 'lib/gcal4ruby/event.rb', line 294

def calendar=(p)
  raise ArgumentError, 'Value must be a valid Calendar object' if not p.is_a? Calendar
  @parent_calendar = p
end

#copyObject

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



181
182
183
184
185
186
# File 'lib/gcal4ruby/event.rb', line 181

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

#createObject

Creates a new event



229
230
231
# File 'lib/gcal4ruby/event.rb', line 229

def create
  service.send_request(GData4Ruby::Request.new(:post, @parent_calendar.content_uri, to_xml))
end

#end_timeObject

The event end time. If a recurring event, the recurrence end time.



216
217
218
# File 'lib/gcal4ruby/event.rb', line 216

def end_time
  return @end_time ? @end_time : @recurrence ? @recurrence.end_time : nil
end

#end_time=(str) ⇒ Object

Sets the end time of the Event. Must be a Time object or a parsable string representation of a time.

Raises:

  • (ArgumentError)


201
202
203
204
205
206
207
208
# File 'lib/gcal4ruby/event.rb', line 201

def end_time=(str)
  raise ArgumentError, "End Time must be either Time or String" if not str.is_a?String and not str.is_a?Time
  @end_time = if str.is_a?String
    Time.parse(str)      
  elsif str.is_a?Time
    str
  end
end

#exists?Boolean

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

Returns:

  • (Boolean)


408
409
410
# File 'lib/gcal4ruby/event.rb', line 408

def exists?
  return @exists
end

#load(string) ⇒ Object

Loads the event info from an XML string.



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
345
# File 'lib/gcal4ruby/event.rb', line 300

def load(string)
  super(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 'id'
        @calendar_id, @id = @feed_uri.gsub("http://www.google.com/calendar/feeds/", "").split("/events/")
        @id = "#{@calendar_id}/private/full/#{@id}"
      when 'edited'
        @edited = Time.parse(ele.text)
      when 'content'
        @content = ele.text
      when "when"
        @start_time = Time.parse(ele.attributes['startTime'])
        @end_time = Time.parse(ele.attributes['endTime'])
        @all_day = !ele.attributes['startTime'].include?('T')
        @reminder = []
        ele.elements.each("gd:reminder") do |r|
          rem = {}
          rem[:minutes] = r.attributes['minutes'] if r.attributes['minutes']
          rem[:method] = r.attributes['method'] if r.attributes['method']
          @reminder << rem
        end
      when "where"
        @where = ele.attributes['valueString']
      when "link"
        if ele.attributes['rel'] == 'edit'
          @edit_feed = ele.attributes['href']
        end
      when "who"        
        @attendees << {:email => ele.attributes['email'], :name => ele.attributes['valueString'], :role => ele.attributes['rel'].gsub("http://schemas.google.com/g/2005#event.", ""), :status => ele.elements["gd:attendeeStatus"] ? ele.elements["gd:attendeeStatus"].attributes['value'].gsub("http://schemas.google.com/g/2005#event.", "") : ""}
      when "eventStatus"
        @status =  ele.attributes["value"].gsub("http://schemas.google.com/g/2005#event.", "").to_sym 
      when 'recurrence'
        @recurrence = Recurrence.new(ele.text)
      when "transparency"
         @transparency = case ele.attributes["value"]
            when "http://schemas.google.com/g/2005#event.transparent" then :free
            when "http://schemas.google.com/g/2005#event.opaque" then :busy
         end
    end      
  end
end

#recurrenceObject

Returns the current event’s Recurrence information



144
145
146
# File 'lib/gcal4ruby/event.rb', line 144

def recurrence
  @recurrence
end

#recurrence=(r) ⇒ Object

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

Raises:

  • (ArgumentError)


175
176
177
178
# File 'lib/gcal4ruby/event.rb', line 175

def recurrence=(r)
  raise ArgumentError, 'Recurrence must be a Recurrence object' if not r.is_a?(Recurrence)
  @recurrence = r
end

#reloadObject

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



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

def reload
  return false if not @exists
  t = Event.find(service, {:id => @id})
  if t and load(t.to_xml)
     return true
  end
  return false
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.

Raises:

  • (CalendarNotEditable)


223
224
225
226
# File 'lib/gcal4ruby/event.rb', line 223

def save
  raise CalendarNotEditable if not calendar.editable
  super
end

#start_timeObject

The event start time. If a recurring event, the recurrence start time.



211
212
213
# File 'lib/gcal4ruby/event.rb', line 211

def start_time
  return @start_time ? @start_time : @recurrence ? @recurrence .start_time : nil
end

#start_time=(str) ⇒ Object

Sets the start time of the Event. Must be a Time object or a parsable string representation of a time.

Raises:

  • (ArgumentError)


190
191
192
193
194
195
196
197
# File 'lib/gcal4ruby/event.rb', line 190

def start_time=(str)
  raise ArgumentError, "Start Time must be either Time or String" if not str.is_a?String and not str.is_a?Time
  @start_time = if str.is_a?String
    Time.parse(str)      
  elsif str.is_a?Time
    str
  end
end

#to_xmlObject

Returns an XML representation of the event.



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
280
281
282
283
284
285
# File 'lib/gcal4ruby/event.rb', line 234

def to_xml()
  xml = REXML::Document.new(super)
  xml.root.elements.each(){}.map do |ele|
    case ele.name
      when "content"
        ele.text = @content
      when "when"
        if not @recurrence
          puts 'all_day = '+@all_day.to_s if service.debug
          if @all_day
            puts 'saving as all-day event' if service.debug 
          else
            puts 'saving as timed event' if service.debug
          end
          ele.attributes["startTime"] = @all_day ? @start_time.strftime("%Y-%m-%d") : @start_time.utc.xmlschema
          ele.attributes["endTime"] = @all_day ? @end_time.strftime("%Y-%m-%d") : @end_time.utc.xmlschema
          set_reminder(ele)
        else
          xml.root.delete_element("/entry/gd:when")
          ele = xml.root.add_element("gd:recurrence")
          ele.text = @recurrence.to_recurrence_string
          set_reminder(ele) if @reminder
        end
      when "eventStatus"
        ele.attributes["value"] = STATUS[@status]
      when "transparency"
        ele.attributes["value"] = TRANSPARENCY[@transparency]
      when "where"
        ele.attributes["valueString"] = @where
      when "recurrence"
        puts 'recurrence element found' if service.debug
        if @recurrence
          puts 'setting recurrence' if service.debug
          ele.text = @recurrence.to_recurrence_string
        else
          puts 'no recurrence, adding when' if service.debug
          w = xml.root.add_element("gd:when")
          xml.root.delete_element("/entry/gd:recurrence")
          w.attributes["startTime"] = @all_day ? @start_time.strftime("%Y-%m-%d") : @start_time.xmlschema
          w.attributes["endTime"] = @all_day ? @end_time.strftime("%Y-%m-%d") : @end_time.xmlschema
          set_reminder(w)
        end
    end
  end        
  if not @attendees.empty?
    xml.root.elements.delete_all "gd:who"
    @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