pusher-client (Ruby)

pusher-client is a ruby gem for consuming WebSockets from the Pusher web service.

The connection to Pusher can optionally be maintained in its own thread (see Asynchronous Usage).

This gem is compatible with jruby since 0.2.

Installation

gem install pusher-client

Single-Threaded Usage

The application will pause at socket.connect and handle events from Pusher as they happen.

require 'pusher-client'

PusherClient.logger = Logger.new(STDOUT)
options = {:secret => YOUR_APP_SECRET}
socket = PusherClient::Socket.new(YOUR_APP_KEY, options)

# Subscribe to a public channel
socket.subscribe('channel')

# Subscribe to an authenticated channel
socket.subscribe('presence-channel', 'user_id')

# Subscribe to an authenticated channel with optional :user_info
socket.subscribe('presence-channel', 'user_id', { :name => 'name' })

# Subscribe to array of channels
['channel1', 'channel2'].each do |c|
  socket.subscribe("presence-#{c}", 'user_id')
end

# Bind to global events (a catch-all for any 'event' across subscribed channels)
socket.bind('event') do |data|
  puts data
end

# Bind to events that occur on a specific channel
socket['channel'].bind('event') do |data|
  puts data
end

socket.connect

Asynchronous Usage

The socket will remain open in the background as long as your main application thread is running, and you can continue to subscribe/unsubscribe to channels and bind new events.

require 'pusher-client'

PusherClient.logger = Logger.new(STDOUT)
options = {:secret => YOUR_APP_SECRET}
socket = PusherClient::Socket.new(YOUR_APP_KEY, options)
socket.connect(true) # Connect asynchronously

# Subscribe to a channel
socket.subscribe('channel')

# Bind to a global event
socket.bind('event') do |data|
  puts data
end

loop do
  sleep(1) # Keep your main thread running
end

For further documentation, read the source & test suite. Some features of the JavaScript client are not yet implemented.

Gotchas

When binding to a global event, note that you still must be subscribed to the channels the event may be sent on. You can’t just bind a global event without subscribing to any channels and call it a day.

Contributing to pusher-client

TODOs

Copyright © 2010 Logan Koester. See LICENSE.txt for further details.