Class: WebSocketHook
- Inherits:
-
Object
- Object
- WebSocketHook
- Defined in:
- lib/websockethook.rb
Constant Summary collapse
- DEFAULT_HOST =
'wss://websockethook.io'- DEFAULT_SLEEP =
0.1- DEFAULT_KEEP_ALIVE =
true- DEFAULT_PING =
20
Instance Attribute Summary collapse
-
#host ⇒ Object
readonly
Returns the value of attribute host.
Instance Method Summary collapse
- #block(&callback) ⇒ Object
-
#initialize(options = {}) ⇒ WebSocketHook
constructor
A new instance of WebSocketHook.
- #initialize_host(options = {}) ⇒ Object
- #listen(id = nil, &callback) ⇒ Object
- #on_message(message, &callback) ⇒ Object
- #on_open(id = nil, &callback) ⇒ Object
- #stop ⇒ Object
- #unblock ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ WebSocketHook
Returns a new instance of WebSocketHook.
12 13 14 15 |
# File 'lib/websockethook.rb', line 12 def initialize( = {}) @stopping = false initialize_host end |
Instance Attribute Details
#host ⇒ Object (readonly)
Returns the value of attribute host.
5 6 7 |
# File 'lib/websockethook.rb', line 5 def host @host end |
Instance Method Details
#block(&callback) ⇒ Object
49 50 51 52 53 54 55 |
# File 'lib/websockethook.rb', line 49 def block(&callback) begin sleep 0.1 end while !@stopping callback.call :stopped @stopping = false end |
#initialize_host(options = {}) ⇒ Object
61 62 63 64 |
# File 'lib/websockethook.rb', line 61 def initialize_host( = {}) @host = [:host] || DEFAULT_HOST fail 'Host (:host) must be a URL' unless @host.is_a?(String) end |
#listen(id = nil, &callback) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/websockethook.rb', line 17 def listen(id=nil, &callback) @ws = WebSocket::Client::Simple.connect(@host) this = self @ws.on(:open) { this.on_open(id, &callback) } @ws.on(:message) {|| this.(, &callback) } @ws.on(:close) { callback.call :closed } @ws.on(:error) { |er| callback.call :error, er } block(&callback) end |
#on_message(message, &callback) ⇒ Object
39 40 41 42 43 44 45 46 47 |
# File 'lib/websockethook.rb', line 39 def (, &callback) if && .data data = JSON.parse(.data) if data['type'] == 'registered' callback.call :registered, data['data'] end callback.call :hook, {'id'=>data['id'], 'data' => data['data']} if data['type'] == 'hook' end end |
#on_open(id = nil, &callback) ⇒ Object
34 35 36 37 |
# File 'lib/websockethook.rb', line 34 def on_open(id=nil, &callback) callback.call :open @ws.send({type:'register', id: id}.to_json) if id end |
#stop ⇒ Object
29 30 31 32 |
# File 'lib/websockethook.rb', line 29 def stop unblock @ws.close end |
#unblock ⇒ Object
57 58 59 |
# File 'lib/websockethook.rb', line 57 def unblock @stopping = true end |