Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@utgarda
Created August 5, 2013 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utgarda/6157547 to your computer and use it in GitHub Desktop.
Save utgarda/6157547 to your computer and use it in GitHub Desktop.
Example of Celluloid::WebSocket::Client usage from inside Sidekiq workers
# Make sure you have Sinatra installed, then start sidekiq with
# sidekiq -r ./sinkiq.rb
# Simply run Sinatra with
# ruby ./sinkiq.rb
# and then browse to http://localhost:4567
#
require 'sinatra'
require 'sidekiq'
require 'redis'
require 'celluloid'
require 'celluloid/websocket/client'
$redis = Redis.connect
class MyWebSocketWhatever
include Celluloid
def initialize(url)
@ws_client = Celluloid::WebSocket::Client.new url, Celluloid::Actor.current
end
def send_message(msg)
@ws_client.text msg
end
def on_message(msg)
$redis.lpush 'sinkiq-example-messages', "RESPONSE: #{msg}"
end
end
class SinatraWorker
include Sidekiq::Worker
def perform(msg='lulz you forgot a msg!')
$redis.lpush 'sinkiq-example-messages', "SENT: #{msg}"
MyWebSocketWhatever.new('ws://echo.websocket.org').send_message msg
end
end
get '/' do
stats = Sidekiq::Stats.new
@failed = stats.failed
@processed = stats.processed
@messages = $redis.lrange('sinkiq-example-messages', 0, -1)
erb :index
end
post '/msg' do
SinatraWorker.perform_async params[:msg]
redirect to('/')
end
__END__
@@ layout
<html>
<head>
<title>Sinatra + Sidekiq</title>
<body>
<%= yield %>
</body>
</html>
@@ index
<h1>Sinatra + Sidekiq Example</h1>
<h2>Failed: <%= @failed %></h2>
<h2>Processed: <%= @processed %></h2>
<form method="post" action="/msg">
<input type="text" name="msg">
<input type="submit" value="Add Message">
</form>
<a href="/">Refresh page</a>
<h3>Messages</h3>
<% @messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment