Ruby API & SDK Docs 5.5.0
In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNubPubNub
PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including:
- Message delivery and persistence
- Presence detection
- Access control
- Push notifications
- File sharing
- Serverless processing with Functions and Events & Actions
- Analytics and monitoring with BizOps Workspace
- AI–powered insights with Illuminate
- Setting up a connection
- Sending messages
- Receiving messages in real-time
Overview
This guide will help you get up and running with PubNub in your Ruby application. You'll learn how to integrate the PubNub Ruby SDK to build real-time features into your applications.
The PubNub Ruby SDK provides a simple API for building real-time applications with features like:
- Publish/subscribe messaging
- Presence detection (online/offline status)
- Storage and playback
- Access control
- Push notifications
Prerequisites
Before we dive in, make sure you have:
- A basic understanding of Ruby
- Ruby 2.7 or later installed
- Bundler for managing dependencies (optional)
- A PubNub account (we'll help you set this up!)
Setup
Get your PubNub keys
First things first – you'll need your PubNub keys to get started. Here's how to get them:
- Sign in or create an account on the PubNub Admin Portal.
- Create a new app (or use an existing one).
- Find your publishand subscribe
Publish Key
A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.keys in the app's dashboard.Subscribe Key
A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.
Install the SDK
SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
Install the PubNub Ruby SDK using RubyGems:
gem install pubnub
Alternatively, if you're using Bundler:
- Create a
Gemfile
in your project directory:
# Gemfile
source 'https://rubygems.org'
gem 'pubnub', '~> 5.5.0'
- Then run:
bundle install
You can also get the source code directly from GitHub.
For a list of supported platforms, see the platform support documentation.
Steps
Initialize PubNub
First, create a new app.rb
file and add the following code to initialize the PubNub client.
Make sure to replace the demo keys with your own publish and subscribe keys from the Admin Portal.
require 'pubnub'
# Initialize PubNub
pubnub = Pubnub.new(
subscribe_key: 'demo',
publish_key: 'demo',
user_id: 'myUniqueUserId',
ssl: true
)
puts "PubNub initialized with user_id: #{pubnub.user_id}"
This creates a new PubNub instance with your keys and a unique user ID. The ssl: true
parameter ensures your connections are secure.
For more information, refer to the Configuration section of the SDK documentation.
Set up event listeners
Next, set up listeners to handle incoming messages, presence events, and connection status updates:
# Define callbacks for different event types
callback = Pubnub::SubscribeCallback.new(
message: ->(envelope) {
puts "MESSAGE: #{envelope.result[:data][:message]['text']}"
},
presence: ->(envelope) {
puts "PRESENCE: #{envelope.result[:data]}"
},
status: ->(envelope) {
if envelope.status[:error]
puts "ERROR: #{envelope.status[:category]}"
else
puts "STATUS: #{envelope.status[:category]}"
end
}
show all 19 linesThe message listener receives and processes incoming messages from subscribed channels. The presence listener handles presence events, such as when users join or leave channels. The status listener provides information about the connection status and any errors.
For more information, refer to the Listeners section of the SDK documentation.
Create a subscription
Now, subscribe to a channel to start receiving messages:
# Subscribe to a channel
pubnub.subscribe(
channels: ['my_channel'],
with_presence: true
)
puts "Subscribed to 'my_channel'"
This code subscribes to the channel my_channel
. The with_presence: true
parameter enables presence events, allowing you to see when users join or leave the channel.
Publish messages
After subscribing, you can publish messages to the channel.
When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.
A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.
# Define a message to publish
message = { text: 'Hello world!' }
# Publish the message
pubnub.publish(
channel: 'my_channel',
message: message
) do |envelope|
if envelope.status[:error]
puts "Publish Error: #{envelope.status[:error]}"
else
puts "Message Published! Timetoken: #{envelope.result[:timetoken]}"
end
end
This publishes a simple message with the text "Hello world!" to the channel my_channel
. The callback handles the response, confirming the message was published or reporting any errors.
Run the app
Now that you've set up all the components, let's put them together and run the application:
- Save your file as
app.rb
. - Run the application with:
ruby app.rb
You should see output similar to:
PubNub initialized with user_id: myUniqueUserId
Subscribed to 'my_channel'
Waiting for messages... (Press Ctrl+C to exit)
STATUS: ack
MESSAGE: Hello world!
PRESENCE: {message: {"action" => "join", "uuid" => "myUniqueUserId", "timestamp" => 1743511468, "precise_timestamp" => 1743511468385, "occupancy" => 4}, subscribed_channel: "my_channel-pnpres", actual_channel: "my_channel-pnpres", publish_time_object: {timetoken: "17435114683856450", region_code: 23}, message_meta_data: {"pn_action" => "join", "pn_channel" => "my_channel", "pn_ispresence" => 1, "pn_occupancy" => 4, "pn_precise_timestamp" => 1743511468385, "pn_timestamp" => 1743511468, "pn_uuid" => "myUniqueUserId"}, presence_event: "join", presence: {uuid: "myUniqueUserId", timestamp: 1743511468, state: nil, occupancy: 4}}
Completed the demonstration
This indicates that:
- PubNub was successfully initialized with your user ID.
- You successfully subscribed to 'my_channel'.
- The application is waiting for messages and events.
- You received a status acknowledgement ('ack') from the PubNub network.
- You received the message with "Hello world!" that was published to the channel.
- You received a presence event showing that your user joined the channel, along with detailed metadata about the event.
- The demonstration completed after running for the specified time.
Complete example
Here's the complete working example that puts everything together:
require 'pubnub'
# Initialize PubNub
pubnub = Pubnub.new(
subscribe_key: 'demo',
publish_key: 'demo',
user_id: 'myUniqueUserId',
ssl: true
)
puts "PubNub initialized with user_id: #{pubnub.user_id}"
# Define callbacks for different event types
callback = Pubnub::SubscribeCallback.new(
message: ->(envelope) {
show all 60 linesTroubleshooting
If you don't see the expected output, here are some common issues and how to fix them:
Issue | Possible Solutions |
---|---|
No connection message |
|
Message not received |
|
Ruby errors |
|
Next steps
Great job! 🎉 You've successfully created your first PubNub Ruby application. Here are some exciting things you can explore next:
- Advanced features
- Real examples
- More help
- Try out Presence to track online/offline status.
- Implement Message Persistence to store and retrieve messages.
- Use Access Manager to secure your channels.
- Explore Channel Groups to organize your channels.
- Implement Push Notifications for mobile applications.
- Explore our GitHub repository for more code samples.
- Check out our Ruby SDK reference documentation for detailed API information.
- Join our Discord community to connect with other developers.
- Visit our support portal for additional resources.
- Ask our AI assistant (the looking glass icon at the top of the page) for help.