Sha256: b782b3687ba7104d4aca7265ec319deac86d439c00e075cda0b4343bacd0771e

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

class Zircon::Message
  def to_json
    fencoding = -> s { s.respond_to?(:force_encoding) ? s.force_encoding('UTF-8') : s }
    {
      username: fencoding.call(from),
      channel: fencoding.call(to),
      body: fencoding.call(body)
    }.to_json
  end
end

class Ircmad
  class WebSocket
    include Configurable

    def initialize(&block)
      instance_eval(&block) if block_given?
    end

    def subscribers
      @subscribers ||= {}
    end

    def host
      '127.0.0.1'
    end

    # http://qiita.com/items/bf47e254d662af1294d8#
    def port
      unless @port || config[:port]
        s = TCPServer.open(0)
        @port = s.addr[1]
        s.close
      end
      @port || config[:port]
    end

    def run!
      puts "Stating WebSocket server on #{host}:#{port}"
      EM::WebSocket.start(:host => host, :port => port) do |socket|
        socket.onopen do |sock|
          subscribers[socket.object_id] = Ircmad.get_channel.subscribe { |msg| socket.send msg.to_json }
        end

        socket.onclose do |sock|
          Ircmad.get_channel.unsubscribe(subscribers[socket.object_id])
        end

        socket.onmessage do |msg|
          Ircmad.post_channel << msg
        end

        socket.onerror do |error|
          puts error
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ircmad-0.0.1 lib/ircmad/web_socket.rb