ruby
53 lines · 10 steps
Building an iCalendar file in Ruby
A small class assembles event details into the RFC 5545 .ics text format, handling escaping and line folding.
Explained by
highlit
1require "securerandom"
2require "time"
3
4class ICalEvent
5 PRODID = "-//Acme Corp//Booking System//EN"
6
7 def initialize(details)
8 @summary = details.fetch(:summary)
9 @starts_at = details.fetch(:starts_at)
10 @ends_at = details.fetch(:ends_at)
11 @description = details[:description]
12 @location = details[:location]
13 @organizer = details[:organizer]
14 @uid = details[:uid] || "#{SecureRandom.uuid}@acme.corp"
15 end
16
17 def to_ics
18 lines = [
19 "BEGIN:VCALENDAR",
20 "VERSION:2.0",
21 "PRODID:#{PRODID}",
22 "CALSCALE:GREGORIAN",
23 "METHOD:PUBLISH",
24 "BEGIN:VEVENT",
25 "UID:#{@uid}",
26 "DTSTAMP:#{format_time(Time.now)}",
27 "DTSTART:#{format_time(@starts_at)}",
28 "DTEND:#{format_time(@ends_at)}",
29 "SUMMARY:#{escape(@summary)}"
30 ]
31 lines << "DESCRIPTION:#{escape(@description)}" if @description
32 lines << "LOCATION:#{escape(@location)}" if @location
33 lines << "ORGANIZER:mailto:#{@organizer}" if @organizer
34 lines << "END:VEVENT"
35 lines << "END:VCALENDAR"
36 lines.map { |line| fold(line) }.join("\r\n") + "\r\n"
37 end
38
39 private
40
41 def format_time(time)
42 time.utc.strftime("%Y%m%dT%H%M%SZ")
43 end
44
45 def escape(text)
46 text.to_s.gsub("\\", "\\\\").gsub("\n", "\\n").gsub(/([,;])/, '\\\\\1')
47 end
48
49 def fold(line)
50 return line if line.bytesize <= 75
51 line.scan(/.{1,74}/m).join("\r\n ")
52 end
53end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Text-based interchange formats are often just carefully assembled and escaped strings, not opaque binaries.
- 2Distinguishing required fields (fetch) from optional ones (bracket access) makes an object's contract explicit.
- 3Standards like iCalendar carry quirks — UTC timestamps, comma escaping, 75-octet line folding — that you must honor for interoperability.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-icalendar-file-in-ruby-explained-ruby-0703/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.