Class: Cryptomarket::Websocket::WSManager

Inherits:
Object
  • Object
show all
Defined in:
lib/cryptomarket/websocket/ws_manager.rb

Overview

websocket connection manager.

Instance Method Summary collapse

Constructor Details

#initialize(handler, url:) ⇒ WSManager

Returns a new instance of WSManager.



13
14
15
16
17
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 13

def initialize(handler, url:)
  @url = url
  @handler = handler
  @connected = false
end

Instance Method Details

#_on_close(_close_event) ⇒ Object



40
41
42
43
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 40

def _on_close(_close_event)
  @handler.on_close
  EM.stop
end

#_on_error(error) ⇒ Object



45
46
47
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 45

def _on_error(error)
  @handler.on_error(error)
end

#_on_message(message) ⇒ Object



49
50
51
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 49

def _on_message(message)
  @handler.handle(JSON.parse(message.data.to_s))
end

#_on_open(_open_event) ⇒ Object



35
36
37
38
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 35

def _on_open(_open_event)
  @connected = true
  @handler.on_open
end

#closeObject



53
54
55
56
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 53

def close
  @ws.close
  @connected = false
end

#connectObject



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 23

def connect
  @thread = Thread.new do
    EM.run do
      @ws = Faye::WebSocket::Client.new(@url)
      @ws.onopen = method(:_on_open)
      @ws.onclose = method(:_on_close)
      @ws.onerror = method(:_on_error)
      @ws.onmessage = method(:_on_message)
    end
  end
end

#connected?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 19

def connected?
  @connected
end

#send(hash) ⇒ Object



58
59
60
61
62
# File 'lib/cryptomarket/websocket/ws_manager.rb', line 58

def send(hash)
  raise Cryptomarket::SDKException.new, 'connection closed' unless @connected

  @ws.send hash.to_json
end