Sha256: 3cebe2021ac7dadc57bc3ab54732240bd483a8da71889a39b2be25584c57aa1c

Contents?: true

Size: 1.09 KB

Versions: 8

Compression:

Stored size: 1.09 KB

Contents

module Jugglite
  class SseConnection
    attr_reader :body, :request

    def initialize(request)
      @request = request
      @longpolling = request.xhr?
      @body = DeferrableBody.new
    end

    def longpolling?
      @longpolling
    end

    def write(message, options = {})
      reset_timeout if longpolling?
      buffer = ""
      options.each { |k, v| buffer << "#{k}: #{v}\n" }
      message.each_line { |line| buffer << "data: #{line.strip}\n" }
      @body.write(buffer << "\n")
    end

    def keepalive(extra=nil)
      # From http://dev.w3.org/html5/eventsource/#notes
      comment("keepalive #{extra}")
    end

    def comment(comment)
      @body.write(": #{comment}\n")
    end

    def close
      @body.succeed
    end

    def callback(&block)
      @body.callback(&block)
    end

    def errback(&block)
      @body.errback(&block)
    end

    private
    def reset_timeout
      # From http://html5doctor.com/server-sent-events/#using-the-polyfill
      @timeout.cancel if @timeout
      @timeout = EventMachine::Timer.new(0.25) do
        self.close
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
jugglite-0.6.0 lib/jugglite/sse_connection.rb
jugglite-0.5.0 lib/jugglite/sse_connection.rb
jugglite-0.4.0 lib/jugglite/sse_connection.rb
jugglite-0.3.0 lib/jugglite/sse_connection.rb
jugglite-0.2.0 lib/jugglite/sse_connection.rb
jugglite-0.1.0 lib/jugglite/sse_connection.rb
jugglite-0.0.4 lib/jugglite/sse_connection.rb
jugglite-0.0.3 lib/jugglite/sse_connection.rb