Class: WebSocketHook

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ WebSocketHook

Returns a new instance of WebSocketHook.



12
13
14
15
# File 'lib/websockethook.rb', line 12

def initialize(options = {})
  @stopping = false
  initialize_host options
end

Instance Attribute Details

#hostObject (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(options = {})
  @host = options[: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) {|message| this.on_message(message, &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 on_message(message, &callback)
  if message && message.data
      data = JSON.parse(message.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

#stopObject



29
30
31
32
# File 'lib/websockethook.rb', line 29

def stop
  unblock
  @ws.close
end

#unblockObject



57
58
59
# File 'lib/websockethook.rb', line 57

def unblock
  @stopping = true
end