Class: Applitools::Connectivity::UniversalClientSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/applitools/universal_sdk/universal_client_socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUniversalClientSocket

Returns a new instance of UniversalClientSocket.



12
13
14
15
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 12

def initialize
  @listeners = {}
  @queue = []
end

Instance Attribute Details

#listenersObject (readonly)

Returns the value of attribute listeners.



10
11
12
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 10

def listeners
  @listeners
end

#queueObject (readonly)

Returns the value of attribute queue.



10
11
12
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 10

def queue
  @queue
end

Instance Method Details

#command(name, fn) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 39

def command(name, fn)
  on(name, ->(payload, key) {
    begin
      log("[#{'COMMAND'.yellow}] #{name}, #{key}, #{JSON.pretty_generate(payload)}")
      result = fn.call(payload)
      emit({name: name, key: key}, {result: result})
    rescue => error
      log("[#{'COMMAND ERROR'.red}] #{error}")
      emit({name: name, key: key}, error.message || error)
    end
  })
end

#connect(uri, ws = ::Faye::WebSocket::Client.new(uri)) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 17

def connect(uri, ws = ::Faye::WebSocket::Client.new(uri))
  @socket = ws

  queue.each {|command| command.call}
  queue.clear

  ws.on :message do |event|
    message = JSON.parse(event.data, {:symbolize_names => true})
    params = [message[:payload], message[:key]]
    find_and_execute_listeners(message[:name], message[:key], params)
  end

  ws.on :close do |event|
    find_and_execute_listeners('close')
  end
end

#emit(message, payload) ⇒ Object



34
35
36
37
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 34

def emit(message, payload)
  command = ->() {@socket.send(serialize(message, payload))}
  @socket ? command.call : queue.push(command)
end

#request(name, payload, cb = nil, key = SecureRandom.uuid) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/applitools/universal_sdk/universal_client_socket.rb', line 52

def request(name, payload, cb = nil, key = SecureRandom.uuid)
  log("[#{'REQUEST'.blue}] #{name}, #{key}, #{JSON.pretty_generate(payload)}")
  emit({name: name, key: key}, payload)
  once({name: name, key: key}, Proc.new {|result|
    cb.call(result[:result] || result[:error] || true) if cb
  })
end