Class: Ircmad::WebSocket

Inherits:
Object
  • Object
show all
Includes:
Configurable
Defined in:
lib/ircmad/web_socket.rb,
lib/ircmad/web_socket/buffer.rb

Defined Under Namespace

Classes: Buffer

Instance Method Summary collapse

Methods included from Configurable

#config, #set

Constructor Details

#initialize(&block) ⇒ WebSocket

Returns a new instance of WebSocket.



7
8
9
# File 'lib/ircmad/web_socket.rb', line 7

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

Instance Method Details

#bufferObject



58
59
60
# File 'lib/ircmad/web_socket.rb', line 58

def buffer
  @buffer ||= Buffer.new
end

#hostObject



15
16
17
# File 'lib/ircmad/web_socket.rb', line 15

def host
  '127.0.0.1'
end

#portObject



20
21
22
23
24
25
26
27
# File 'lib/ircmad/web_socket.rb', line 20

def port
  unless @port || config[:port]
    s = TCPServer.open(0)
    @port = s.addr[1]
    s.close
  end
  @port || config[:port]
end

#run!Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ircmad/web_socket.rb', line 29

def run!
  puts "Stating WebSocket server on #{host}:#{port}"

  Ircmad.get_channel.subscribe do |msg|
    buffer << msg
  end

  EM::WebSocket.start(:host => host, :port => port) do |socket|
    socket.onopen do |sock|
      buffer.each do |msg|
        socket.send msg.to_json
      end
      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

#subscribersObject



11
12
13
# File 'lib/ircmad/web_socket.rb', line 11

def subscribers
  @subscribers ||= {}
end