Getting started: Pub/Sub in Ruby
This guide will get you started with Ably Pub/Sub in Ruby.
It will take you through the following steps:
- Create a client and establish a realtime connection to Ably.
- Attach to a channel and subscribe to its messages.
- Publish a message to the channel for your client to receive.
- Join and subscribe to the presence set of the channel.
- Retrieve the messages you sent in the guide from history.
- Close a connection to Ably when it is no longer needed.
Prerequisites
- Sign up for an Ably account.
- Create a new app and get your API key from the dashboard.
- Your API key will need the
publish
,subscribe
,presence
andhistory
capabilities.
- Install the Ably CLI:
npm install -g @ably/cli
CopyCopied!
- Run the following to log in to your Ably account and set the default app and API key:
ably login
ably apps switch
ably auth keys switch
CopyCopied!
- Install Ruby version 2.7 or greater.
- Create a new project and install the Ably Pub/Sub Ruby SDK :
# Create a new Gemfile
echo "source 'https://rubygems.org'" > Gemfile
echo "gem 'ably'" >> Gemfile
# Install the gem
bundle install
CopyCopied!
The realtime interface of the Ruby SDK must be run within an EventMachine reactor which provides an asynchronous evented framework for the library. All functionality within this guide runs within an EventMachine.run
block.
Step 1: Connect to Ably
Clients establish a connection with Ably when they instantiate an SDK instance. This enables them to send and receive messages in realtime across channels.
- Open up the dev console of your first app before instantiating your client so that you can see what happens.
- Create a
get_started.rb
file in your project and add the following function to instantiate the SDK and establish a connection to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use token authentication in a production app. Aclient_id
ensures the client is identified, which is required to use certain features, such as presence:
require 'ably'
require 'eventmachine'
def get_started
EventMachine.run do
# Initialize the Ably Realtime client
realtime_client = Ably::Realtime.new(key: '<loading API key, please wait>', client_id: 'my-first-client')
# Wait for the connection to be established
realtime_client.connection.on(:connected) do
puts "Made my first connection!"
end
end
end
get_started
Demo OnlyCopyCopied!
You can monitor the lifecycle of clients’ connections by registering a listener that will emit an event every time the connection state changes. For now, run the function with ruby get_started.rb
to log a message to the console to know that the connection attempt was successful. You’ll see the message printed to your console, and you can also inspect the connection event in the dev console of your app.
Messages contain the data that a client is communicating, such as a short ‘hello’ from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to.
- Add the following lines to your
get_started
method within theEventMachine
to create a channel instance and register a listener to subscribe to the channel. Then run it withruby get_started.rb
:
# Get a channel instance
channel = realtime_client.channels.get('my-first-channel')
# Subscribe to messages on the channel
channel.subscribe do |message|
puts "Received message: #{message.data}"
end
CopyCopied!
- Use the Ably CLI to publish a message to your first channel. The message will be received by the client you’ve subscribed to the channel, and be logged to the console.
ably channels publish my-first-channel 'Hello!' --name "myEvent"
CopyCopied!
- In a new terminal tab, subscribe to the same channel using the CLI:
ably channels subscribe my-first-channel
CopyCopied!
Publish another message using the CLI and you will see that it’s received instantly by the client you have running locally, as well as the subscribed terminal instance.
To publish a message in your code, you can add the following line to your get_started
method after subscribing to the channel:
channel.publish '', 'A message sent from my first client!'
CopyCopied!
Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline.
- Add the following lines to your
get_started
method to subscribe to, and join, the presence set of the channel. Then run it withruby get_started.rb
:
# Subscribe to presence events on the channel
channel.presence.subscribe do |member|
puts "Event type: #{member.action} from #{member.client_id} with the data #{member.data.inspect}"
end
# Enter the presence set
channel.presence.enter("I'm here!")
CopyCopied!
- You can have another client join the presence set using the Ably CLI:
ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"learning about Ably!"}'
CopyCopied!
You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required.
If more than 2 minutes has passed since you published a regular message (excluding the presence events), then publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this.
For example, using the Ably CLI to publish 5 messages:
ably channels publish --count 5 my-first-channel "Message number {{.Count}}" --name "myEvent"
CopyCopied!
- Add the following lines to your
get_started
method to retrieve any messages that were recently published to the channel. Then run it withruby get_started.rb
:
# Retrieve message history
channel.history do |messages_page|
puts messages_page.items.map { |message| message.data }
end
CopyCopied!
The output will look similar to the following:
[
'Message number 5',
'Message number 4',
'Message number 3',
'Message number 2',
'Message number 1'
]
CopyCopied!
Step 5: Close the connection
Connections are automatically closed approximately 2 minutes after no heartbeat is detected by Ably. Explicitly closing connections when they are no longer needed is good practice to help save costs. It will also remove all listeners that were registered by the client.
Note that messages are streamed to clients as soon as they attach to a channel, as long as they have the necessary capabilities. Clients are implicitly attached to a channel when they call subscribe()
. Detaching from a channel using the detach()
method will stop the client from being streamed messages by Ably.
Listeners registered when subscribing to a channel are registered client-side. Unsubscribing by calling unsubscribe()
will remove previously registered listeners for that channel. Detaching from a channel has no impact on listeners. As such, if a client reattaches to a channel that they previously registered listeners for, then those listeners will continue to function upon reattachment.
- Add the following to your client to close the connection after a simulated 10 seconds. Run it with
ruby get_started.rb
:
# Close the connection after 10 seconds
EventMachine.add_timer(10) do
# Close the connection after 10 seconds
realtime_client.close
EventMachine.stop
puts "Connection closed after 10 seconds."
end
CopyCopied!
Next steps
Continue to explore the documentation with Ruby as the selected language:
Read more about the concepts covered in this guide:
- Revisit the basics of Pub/Sub
- Explore more advanced Pub/Sub concepts
- Understand realtime connections to Ably
- Read more about how to use presence in your apps
- Fetch message history in your apps
You can also explore the Ably CLI further, or visit the Pub/Sub API references.