I have a simple Sinatra App running on EventMachine, like this example.
The app is working, now I’d like to allow the routes I’m defining in Sinatra to access the websocket using the EventMachine channel that is created. I naively tried the following, but of course within the Sinatra App, the @channel variable isn’t defined, so this doesn’t work.
require 'em-websocket'
require 'sinatra'
EventMachine.run do
@channel = EM::Channel.new
class App < Sinatra::Base
get '/' do
erb :index
end
post '/test' do
@channel.push "Post request hit endpoint"
status 200
end
end
EventMachine::WebSocket.start :host => '0.0.0.0', :port => 8080 do |socket|
socket.onopen do
sid = @channel.subscribe { |msg| socket.send msg }
@channel.push "Subscriber ID #{sid} connected!"
socket.onmessage do |msg|
@channel.push "Subscriber <#{sid}> sent message: #{msg}"
end
socket.onclose do
@channel.unsubscribe(sid)
end
end
end
App.run! :port => 3000
end
How could I access the EventMachine channel I’ve got open within my Sinatra app?
In case others don’t know what we’re talking about in the comments, here’s an example of using a class instance variable in the way I suggested. This runs, but I don’t know if it does what’s expected: