Class: Strut::SlimClient

Inherits:
Object
  • Object
show all
Defined in:
lib/strut/slim_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port, max_attempts) ⇒ SlimClient

Returns a new instance of SlimClient.



6
7
8
9
10
# File 'lib/strut/slim_client.rb', line 6

def initialize(host, port, max_attempts)
  @host = host
  @port = port
  @max_attempts = max_attempts
end

Instance Method Details

#decode_response(response) ⇒ Object



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

def decode_response(response)
  ListDeserializer.deserialize(response)
end

#encode_commands(commands) ⇒ Object



21
22
23
24
25
26
# File 'lib/strut/slim_client.rb', line 21

def encode_commands(commands)
  flattened_commands = commands.map { |c| c.to_a }
  serialised_commands = ListSerializer.serialize(flattened_commands)
  length = ListSerializer.length_string(serialised_commands.length)
  "#{length}#{serialised_commands}"
end

#prepare_socketObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/strut/slim_client.rb', line 28

def prepare_socket
  socket = nil
  attempts = 0
  while socket.nil? and attempts < @max_attempts do
    begin
      socket = TCPSocket.open(@host, @port)
    rescue
      attempts += 1
      sleep(2)
    end
  end
  throw "Could not connect to Slim server." if socket.nil?
  socket
end

#read_and_ignore_version(socket) ⇒ Object



43
44
45
# File 'lib/strut/slim_client.rb', line 43

def read_and_ignore_version(socket)
  socket.gets
end

#read_response(socket) ⇒ Object



51
52
53
54
55
# File 'lib/strut/slim_client.rb', line 51

def read_response(socket)
  length = socket.read(6).to_i  # <length>
  socket.read(1)                # :
  socket.read(length)           # <command>
end

#responses_for_commands(commands) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/strut/slim_client.rb', line 12

def responses_for_commands(commands)
  encoded_commands = encode_commands(commands)
  socket = prepare_socket
  read_and_ignore_version(socket)
  write_commands(socket, encoded_commands)
  response = read_response(socket)
  decode_response(response)
end

#write_commands(socket, commands) ⇒ Object



47
48
49
# File 'lib/strut/slim_client.rb', line 47

def write_commands(socket, commands)
  socket.puts(commands)
end