dynamically create an ical / ics file from a rails model

9.6k views Asked by At

Given that I have the following data for an event as a hash in ruby on rails :

event = {
  start_at: Time.now(),
  end_at: Time.now() + 3600,
  summary: 'My meeting',
  description: 'A zoom meeting about food',
  event_url: 'https://food.example.com',
  formatted_address: ''
}

How do I deliver that info to a user a dynamically created an ical/ics file?

1

There are 1 answers

0
Philip Hallstrom On BEST ANSWER

The icalendar gem works well. https://github.com/icalendar/icalendar

I use this to generate outlook and ical versions. Works great.

cal = Icalendar::Calendar.new
filename = "Foo at #{foo.name}"

if params[:format] == 'vcs'
  cal.prodid = '-//Microsoft Corporation//Outlook MIMEDIR//EN'
  cal.version = '1.0'
  filename += '.vcs'
else # ical
  cal.prodid = '-//Acme Widgets, Inc.//NONSGML ExportToCalendar//EN'
  cal.version = '2.0'
  filename += '.ics'
end

cal.event do |e|
  e.dtstart     = Icalendar::Values::DateTime.new(foo.start_at, tzid: foo.time_zone)
  e.dtend       = Icalendar::Values::DateTime.new(foo.end_at, tzid: foo.course.time_zone)
  e.summary     = foo.summary
  e.description = foo.description
  e.url         = event_url(foo)
  e.location    = foo.formatted_address
end

send_data cal.to_ical, type: 'text/calendar', disposition: 'attachment', filename: filename