How to manage calendar events with the Ruby SDK

How to manage calendar events with the Ruby SDK

9 min read

In today’s busy world, it’s critical to have an organized schedule and that means managing calendars and events. Thanks to Nylas’ Ruby SDK, this becomes a simple and productive task. We can manage calendar events with ease using Ruby.

What are we going to talk about?

Creating the .env file

Every project is going to need a .env file, and its content is going to be the same unless indicated.

V3_TOKEN_API=<YOUR_TOKEN_API>
CALENDAR_ID=<YOUR_CALENDAR_ID>
GRANT_ID=<YOUR_GRANT_ID>

Reading calendars

Let’s start by reading a list of calendars, looking at the calendar id, name, and description. We are going to create a file called ReadCalendarsV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas'

# Initialize Nylas client
nylas = Nylas::Client.new(
	api_key: ENV["V3_TOKEN"]
)

# Get a list of calendars
calendars, _request_ids = 
nylas.calendars.list(identifier: ENV["GRANT_ID"], query_params: {})

# Print the Id, Name and Description
calendars.each {|calendar|
	puts("Id: #{calendar[:id]} | " \
	        "Name: #{calendar[:name]} | " \
	        "Description: #{calendar[:description]}")
}

We can run it by calling it from our terminal window:

$ ruby ReadCalendarsV3.rb
Reading Calendars

Now, there’s a new feature included in V3, which is the ability to get calendar colours:

To showcase this functionality, we’re going to use the Ruby 2D gem:

$ gem install ruby2d

And we’re going to create a new script named ReadCalendarColorsV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas'
require 'ruby2d'

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Define the window's width and height
set width: 1500
set height: 300
# Global variable to increase the y position of the window
y = 10

# Call a list of calendars
calendars, _request_ids = nylas.calendars.list(identifier: ENV["GRANT_ID"], query_params: {})

# Print the Id, Name and Description
calendars.each {|calendar|
    Text.new("Id: #{calendar[:id]} | " \
                   "Name: #{calendar[:name]} | " \
                   "Description: #{calendar[:description]}",
    x: 0, y: y, color: calendar[:hex_color])
    # Add y to separate each line
    y = y + 25
}

# Display the window
show

We can run it by calling it from our terminal window:

$ ruby ReadCalendarsColorV3.rb
Reading Calendars with colour

Creating Calendars

Sometimes, we need to create a new calendar to keep events separated. Let’s create a new file called CreateCalendarV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas' 

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Body parameters
request_body = {
    "name": "My New Calendar",
    "description": "Description of my new calendar",
    "location": "Location description",
    "timezone": "America/Toronto"
}

# Create new calendar
calendars, _request_ids = nylas.calendars.create(identifier: ENV["GRANT_ID"], query_params: {}, request_body: request_body)
 
# Print calendar information 
puts calendars

We can run it by calling it from our terminal window:

$ ruby CreateCalendarV3.rb

Updating Calendars

We just created a calendar but realized we did something wrong or maybe we don’t like the assigned colour. Let’s create a file called UpdateCalendarV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas' 

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Body parameters
request_body = {
    "name": "My New Calendar",
    "description": "Description of my new calendar",
    "location": "Location description",
    "timezone": "America/Toronto",
    "hex_color": "#039BE5"
}

# Create new calendar
calendars, _request_ids = nylas.calendars.update(identifier: ENV["GRANT_ID"], object_id: "<CALENDARD_ID>",
query_params: {}, request_body: request_body)
 
# Print calendar information 
puts calendars

We can run it by calling it from our terminal window:

$ ruby UpdateCalendarV3.rb
Update a Calendar

Deleting Calendars

Just like we can create and update calendars, we can delete them. So, let’s do that. Create a file called DeleteCalendarV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas' 

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"],
    api_uri: ENV["V3_HOST"]
)

# Create new calendar
result, _request_ids = nylas.calendars.destroy(identifier: ENV["GRANT_ID"], object_id: "<CALENDAR_ID>", query_params: {})
 
# Print result information 
puts result

We can run it by calling it from our terminal window:

$ ruby DeleteCalendarV3.rb
Delete a Calendar

Getting Availability

Before jumping into events, let’s take a look at an important calendar component. Getting available spots would help us if we were developing a schedule application or if we would want to let our users know when we are available for them.

Let’s create a file named GetAvailabilityV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas'
require 'date'

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Get today’s date
today = Date.today

# When do we start and end searching for availability
start_time = Time.local(today.year, today.month, today.day, 8, 0,0).strftime("%s").to_i
end_time = Time.local(today.year, today.month, today.day, 17, 0,0).strftime("%s").to_i

# Body of our request
request_body = {
    "participants": [
        {
        "email": ENV["GRANT_ID"],
            "calendar_ids": [
                ENV["CALENDAR_ID"]
            ],
        },
    ],
    "start_time": start_time,
    "end_time": end_time,
    "duration_minutes": 60,
}

# Call the get_availability endpoint
available, _request_ids = nylas.calendars.get_availability(request_body: request_body)
# Display available spots
available[:time_slots].each {|slots|
    puts "From: #{Time.at(slots[:start_time]).to_datetime.strftime("%H:%M:%S")}" \
            " To: #{Time.at(slots[:end_time]).to_datetime.strftime("%H:%M:%S")}"
}

We can run it by calling it from our terminal window:

$ ruby GetAvailabilityV3.rb
Getting Calendar availability

Reading events

Working with calendars is important, but working with events is mandatory. We might create one or two calendars, but when it comes to events, we create and receive a lot of them during the week. So it’s important to be able to manage them accordingly.

We’re going to read the events from our main calendar. Let’s create a file named ReadEventsV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas'
#require 'date'

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Get today’s date
today = Date.today

# Query parameters
query_params = {
    calendar_id: ENV["CALENDAR_ID"],
    limit: 5
}

# Start and End date to filter our events
query_params['start'] = Time.local(today.year, today.month, today.day, 8, 0,0).strftime("%s")
query_params['end'] = Time.local(today.year, today.month, today.day, 22, 0,0).strftime("%s")

# Read events from our main calendar in the specified date and time
events, _request_ids = nylas.events.list(identifier: ENV["GRANT_ID"], query_params: query_params)
#events, _request_ids = nylas.events.list(identifier: "[email protected]", query_params: query_params)

# Loop events
events.each {|event|
    case event[:when][:object]
        when 'timespan'
            start_time = Time.at(event[:when][:start_time]).strftime("%d/%m/%Y at %H:%M:%S")
            end_time = Time.at(event[:when][:end_time]).strftime("%d/%m/%Y at %H:%M:%S")
            event_date = "The time of the event is from: #{start_time} to #{end_time}"
        when 'datespan'
            start_time = event[:when][:start_date]
            end_time = event[:when][:end_date]
            event_date = "The date of the event is from: #{start_time} to: #{end_time}"
        when 'date'
            start_time = event[:when][:date]
            event_date = "The date of the event is: #{start_time}"
        end
        participant_details = ""
        event[:participants].each {|participant|
            participant_details += "Email: #{participant[:email]} Name: #{participant[:name]} Status: #{participant[:status]} - "
        }
        puts "Id: #{event[:id]} | Title: #{event[:title]} | #{event_date} | Participants: #{participant_details.chomp(' - ')}"
        #puts "Id: #{event[:id]} | Title: #{event[:title]}"  #| #{event_date}"
        puts "\n"
        puts "#{event}"
        puts "\n"
}

We can run it by calling it from our terminal window:

$ ruby ReadEventsV3.rb
Read Calendar events

Creating Events

Creating events is an important task because we might want to invite people to a party, meetup or lunch. Also, by creating events we can send notifications to the participants, instead of just promoting our event online. We’re going to create a file named CreateEventsV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas'

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"],
    api_uri: ENV["V3_HOST"]
)

# Query parameters
query_params = {
    calendar_id: ENV["GRANT_ID"]
}

# Get today’s date
today = Date.today
# Define the time of the event
start_time = Time.local(today.year, today.month, today.day, 10, 0,0).strftime("%s")
end_time = Time.local(today.year, today.month, today.day, 12, 0,0).strftime("%s")

# Request Body
request_body = {
    when: {
        start_time: start_time.to_i,
        end_time: end_time.to_i
    },
    title: "Let's learn some Nylas Ruby SDK!",
    location: "Blag's Den!",
    description: "Using the Nylas API with the Ruby SDK is easy. Come join us!\"",
    participants: [{
        name: "Blag",
        email: "[email protected]", 
        status: 'noreply'
      }]
}

# Read events from our main calendar in the specified date and time
events, _request_ids = nylas.events.create(identifier: ENV["GRANT_ID"], query_params: query_params, request_body: request_body)
if _request_ids != "" 
    puts events[:id]
    puts events[:title]
    puts "Event created successfully"
else
   puts "There was an error creating the event"
end

We can run it by calling it from our terminal window:

$ ruby CreateEventsV3.rb
Create an event

Updating Events

Once an event has been created, it can be easily updated by providing the event ID. Let’s create a file named UpdateEventsV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas'

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Body parameters
request_body = {
    location: "Nylas Headquarters!",
}

# Query parameters
query_params = {
    calendar_id: ENV["GRANT_ID"]
}

# Read events from our main calendar in the specified date and time
event, _request_ids = nylas.events.update(identifier: ENV["GRANT_ID"], event_id: '<EVENT_ID>', query_params: query_params, request_body: request_body)
puts event[:title]
puts event[:location]

We can run it by calling it from our terminal window:

$ ruby UpdateEventsV3.rb

Deleting Events

Just like we can create and update events, we can delete them. So, let’s do that. Create a file named DeleteEventsV3.rb:

# Load gems
require 'dotenv/load'
require 'nylas' 

# Initialize Nylas client
nylas = Nylas::Client.new(
    api_key: ENV["V3_TOKEN"]
)

# Query parameters
query_params = {
    calendar_id: ENV["GRANT_ID"]
}

# Create new calendar
result, _request_ids = nylas.events.destroy(identifier: ENV["GRANT_ID"], event_id: "t6cdduum8q204cgb5if9ta4ifg", query_params: query_params)
 
# Print result information 
puts result

We can run it by calling it from our terminal window:

$ ruby DeleteEventsV3.rb
Delete an event

What’s Next?

Now that we know how we can manage calendar events using Ruby, let’s create a Nylas account and start building.

Do you have any comments or feedback? Please use our forums 😎

You can sign up for Nylas for free and start building!

Also, don’t miss the action, join our LiveStream Coding with Nylas!

Related resources

How to build a CRM in 3 sprints with Nylas

What is a CRM? CRM stands for Customer Relationship Management, and it’s basically a way…

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.

Beyond APIs: Designing elegant, smart Web Components

Dive into the world of smart Web Components for advanced API integration solutions. Design elegant, customizable elements to elevate user experiences.