How to start EventMachine and serve pages in Sinatra?

I am creating a Sinatra application that uses TweetStream (which listens to Tweets using EventMachine). I would also like the application to render pages like a normal Sinatra application, but it looks like Sinatra cannot "listen" to page requests when it "listens" to tweets.

Can I fix this using another server or structuring my application differently? I tried using WebBrick and Thin.

Here is basically what I am doing:

class App < Sinatra::Base

  # listening for tweets
  @client = TweetStream::Client.new
  @client.track(terms) do |status|
    # do some stuff when I detect terms
  end  

  get '/' do
    "Here some page content!"
  end

end
+4
source share
2 answers

Sinatra eventmachine ( awebserver, EM, .. Thin). EM Sinatra, EM.

Sinatra :

http://recipes.sinatrarb.com/p/embed/event-machine

:

require 'eventmachine'
require 'sinatra/base'
require 'thin'

def run(opts)

  EM.run do
    server  = opts[:server] || 'thin'
    host    = opts[:host]   || '0.0.0.0'
    port    = opts[:port]   || '8181'
    web_app = opts[:app]

    dispatch = Rack::Builder.app do
      map '/' do
        run web_app
      end
    end

    unless ['thin', 'hatetepe', 'goliath'].include? server
      raise "Need an EM webserver, but #{server} isn't"
    end

    Rack::Server.start({
      app:    dispatch,
      server: server,
      Host:   host,
      Port:   port
    })
  end
end

class HelloApp < Sinatra::Base

  configure do
    set :threaded, false
  end

  get '/hello' do
    'Hello World'
  end

  get '/delayed-hello' do
    EM.defer do
      sleep 5
    end
    'I\'m doing work in the background, but I am still free to take requests'
  end
end

run app: HelloApp.new
+5

, , sinatra.

, Twitter - sinatra, - , redis db, - .

0