Search code examples
rubywebsocketsinatrafaye

Simple way to integrate Faye with Sinatra in a single file?


Is there a simple way to integrate Faye with Sinatra in a single file like this:

# myapp.rb
require 'sinatra'
require 'faye'

get '/' do 
  'Hello world!' 
end

get '/faye_form' do
  erb :form_and_message_list
end

post '/faye_form' do
  erb :form_and_message_list
  # will send messages to faye's channel here.
end

ruby myapp.rb

so that when I run "ruby myapp.rb" I run in a single process Faye and Sinatra servers (they will be on the same port I guess?) ?

or: what's the closest thing to this, with the purpose of integrating Faye in Sinatra in the most "minimalistic" way ?

update: fixed example code, so that it doesn't look like I am interested in having Faye and Sinatra under the same path ;)


Solution

  • Adapted from http://faye.jcoglan.com/ruby.html

    # config.ru
    require 'sinatra'
    require 'faye'
    require File.expand_path('../app', __FILE__)
    
    use Faye::RackAdapter, :mount => '/faye', :timeout => 25
    
    run Sinatra::Application
    

    Both Sinatra and Faye are rack apps, and you probably want them running on different paths, like with Faye at /faye. You could also mount faye at / and your Sinatra app somewhere else, although I think you'll need to create a "modular" Sinatra app to do that, and then something like:

    run Rack::URLMap.new("/app" => MyApp.new)
    

    In your example, you're sort of trying to have them both under the same path, which I don't think will work.