Class: WebsocketMessaging::Channel

Inherits:
Object
  • Object
show all
Defined in:
lib/websocket_messaging/channel.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id) {|_self| ... } ⇒ Channel

Returns a new instance of Channel.

Yields:

  • (_self)

Yield Parameters:



7
8
9
10
11
12
13
14
15
# File 'lib/websocket_messaging/channel.rb', line 7

def initialize(id)
  @notifier = Notifier.new(id)
  @handlers = {
    before_send: ->(data) { data },
    onmessage:   ->(data) {}
  }

  yield self if block_given?
end

Instance Attribute Details

#notifierObject (readonly)

Returns the value of attribute notifier.



5
6
7
# File 'lib/websocket_messaging/channel.rb', line 5

def notifier
  @notifier
end

#socketObject (readonly)

Returns the value of attribute socket.



5
6
7
# File 'lib/websocket_messaging/channel.rb', line 5

def socket
  @socket
end

Instance Method Details

#before_send(&handler) ⇒ Object



48
49
50
# File 'lib/websocket_messaging/channel.rb', line 48

def before_send(&handler)
  @handlers[:before_send] = handler
end

#onmessage(&handler) ⇒ Object



44
45
46
# File 'lib/websocket_messaging/channel.rb', line 44

def onmessage(&handler)
  @handlers[:onmessage] = handler
end

#start(socket) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/websocket_messaging/channel.rb', line 17

def start(socket)
  @socket = socket

  subscribe_notifier
  subscribe_socket_messages
  subscribe_socket_closed
end

#subscribe_notifierObject



25
26
27
28
29
# File 'lib/websocket_messaging/channel.rb', line 25

def subscribe_notifier
  notifier.subscribe do |data|
    send_socket_message(data)
  end
end

#subscribe_socket_closedObject



38
39
40
41
42
# File 'lib/websocket_messaging/channel.rb', line 38

def subscribe_socket_closed
  socket.onclose do
    notifier.unsubscribe
  end
end

#subscribe_socket_messagesObject



31
32
33
34
35
36
# File 'lib/websocket_messaging/channel.rb', line 31

def subscribe_socket_messages
  socket.onmessage do |message|
    data = JSON.parse(message)
    receive_message(data)
  end
end