Sha256: daadea062173b382bb8e6c4cfeaaa1f28885125aa4707554af5bef43b6d6b7c5

Contents?: true

Size: 1.67 KB

Versions: 5

Compression:

Stored size: 1.67 KB

Contents

module Sinatra

  class Application

    helpers do
      def cometio_js
        "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}#{env['SCRIPT_NAME']}/cometio/cometio.js"
      end
    end

    get '/cometio/cometio.js' do
      content_type 'application/javascript'
      @js ||= (
               js = nil
               File.open(File.expand_path '../js/cometio.js', File.dirname(__FILE__)) do |f|
                 js = f.read
               end
               cometio_url = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}#{env['SCRIPT_NAME']}/cometio/io"
               ERB.new(js).result(binding)
               )
    end

    get '/cometio/io' do
      stream :keep_open do |s|
        session = params[:session].to_s.empty? ? CometIO.create_session : params[:session]
        CometIO.sessions[session][:stream] = s
        CometIO.sessions[session][:last] = Time.now
        CometIO.emit :connect, session if params[:session].to_s.empty?

        unless CometIO.sessions[session][:queue].empty?
          begin
            s.write CometIO.sessions[session][:queue].shift.to_json
            s.flush
            s.close
          rescue
            s.close
          end
        end
        
        EM::add_timer 10 do
          begin
            s.write({:type => :__heartbeat, :data => {:time => Time.now.to_i}}.to_json)
            s.flush
            s.close
          rescue
            s.close
          end
        end
      end
    end

    post '/cometio/io' do
      type = params[:type]
      data = params[:data]
      from = params[:session]
      CometIO.emit type, data, from if type.size > 0
      {:session => session, :type => type, :data => data}.to_json
    end
    
  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
sinatra-cometio-0.0.6 lib/sinatra/application.rb
sinatra-cometio-0.0.5 lib/sinatra/application.rb
sinatra-cometio-0.0.4 lib/sinatra/application.rb
sinatra-cometio-0.0.3 lib/sinatra/application.rb
sinatra-cometio-0.0.2 lib/sinatra/application.rb