Skip to content

Instantly share code, notes, and snippets.

@fractaloop
Created December 14, 2011 23:01
Show Gist options
  • Save fractaloop/1478989 to your computer and use it in GitHub Desktop.
Save fractaloop/1478989 to your computer and use it in GitHub Desktop.
Rails 3.1 Sinatra streaming question...
require 'sinatra'
require 'thin'
class Metaserver < Sinatra::Base
set server: 'thin'
set connections: []
get '/stream', provides: 'text/event-stream' do
stream :keep_open do |out|
settings.connections << out
out.callback { settings.connections.delete(out) }
out.errback { settings.connections.delete out }
end
end
post '/stream' do
puts "Relay to #{settings.connections.count} streams"
settings.connections.each { |out| out << "data: #{params[:msg]}\n\n" }
204 # response without entity body
end
end
require 'metaserver'
Metaverse::Application.routes.draw do
match '/stream', :to => Metaserver
resource :login, :only => :show
resource :explore, :only => :show, :controller => 'explore'
root :to => 'login#show'
end
@baronlinden
Copy link

Is this supposed to work on Rails?

I get a similar example to work when only running the Sinatra app by itself. When I run it mounted inside a Rails app, it fails in creating a persistent connection and tries to reconnect continuously.

@fractaloop
Copy link
Author

Yea, I was pasting this as a question. It turns out you need to mount the Sinatra app first in a rackup file, and then load rails after that.

@baronlinden
Copy link

I tried mounting the Sinatra app as a Rack middleware in my Rails app and that worked. Cheers.

@vicentereig
Copy link

@baronlinden How did you do that? I am mounting it from application.rb , did you mounted it directly at config.ru and worked?

@fedesoria
Copy link

You need to add this to your application.rb

config.preload_frameworks = true
config.allow_concurrency = true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment