Class: ProcessBot::ClientSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/process_bot/client_socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options:) ⇒ ClientSocket

Returns a new instance of ClientSocket.



6
7
8
# File 'lib/process_bot/client_socket.rb', line 6

def initialize(options:)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/process_bot/client_socket.rb', line 4

def options
  @options
end

Instance Method Details

#clientObject



10
11
12
# File 'lib/process_bot/client_socket.rb', line 10

def client
  @client ||= Socket.tcp("localhost", options.fetch(:port).to_i, connect_timeout: 2)
end

#closeObject



14
15
16
# File 'lib/process_bot/client_socket.rb', line 14

def close
  client.close
end

#loggerObject



18
19
20
# File 'lib/process_bot/client_socket.rb', line 18

def logger
  @logger ||= ProcessBot::Logger.new(options: options)
end

#send_command(data) ⇒ Object

rubocop:disable Metrics/AbcSize



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/process_bot/client_socket.rb', line 22

def send_command(data) # rubocop:disable Metrics/AbcSize
  logger.log "Sending: #{data}"
  client.puts(JSON.generate(data))
  response_raw = client.gets

  # Happens if process is interrupted
  return :nil if response_raw.nil?

  response = JSON.parse(response_raw)

  return :success if response.fetch("type") == "success"

  if response.fetch("type") == "error"
    error = RuntimeError.new("Command raised an error: #{response.fetch("message")}")
    error.set_backtrace(response.fetch("backtrace") + Thread.current.backtrace)

    raise error
  end
end