Class: Polytalk::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/polytalk/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Server

Returns a new instance of Server.



7
8
9
10
# File 'lib/polytalk/server.rb', line 7

def initialize(config = {})
  @port = config['port'] || 9090
  @host = config['host'] || '127.0.0.1'
end

Instance Method Details

#call(request) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/polytalk/server.rb', line 22

def call(request)
  required_constant = nil
  request[:class].split('::').each_with_index do |c, index|
    if index == 0
      required_constant = Kernel.const_get(c)
    else
      required_constant = required_constant.const_get(c)
    end
  end

  # Convert string prefixed with `:` to symbols
  if request[:arguments].is_a? Hash
    request[:arguments].each do |key, arg|
      if arg.is_a? String
        if arg.match(/^:/)
          request[:arguments][key] = arg[1..-1].to_sym
        end
      end
    end
  end

  required_method = required_constant.method(request[:method])

  if request[:arguments].is_a? Hash
    required_method.call *request[:arguments].values
  else
    required_method.call
  end
end

#push(connection, response) ⇒ Object



52
53
54
55
# File 'lib/polytalk/server.rb', line 52

def push(connection, response)
  connection.write(response.to_json)
  connection.close
end

#runObject



12
13
14
15
16
17
18
19
20
# File 'lib/polytalk/server.rb', line 12

def run
  server = TCPServer.new(@host, @port)
  loop do
    Thread.start(server.accept) do |connection|
      request = connection.recv(2048)
      yield(connection, JSON.parse(request, symbolize_names: true))
    end
  end
end