Class: RoadToRubykaigi::GameServer

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Singleton
Defined in:
lib/road_to_rubykaigi/game_server.rb

Constant Summary collapse

HOST =
'http://127.0.0.1'
PORT =
2026
ENDPOINT =
'/road_to_rubykaigi'
MAX_AGE_SECONDS =
0.5

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#queueObject (readonly)

Returns the value of attribute queue.



18
19
20
# File 'lib/road_to_rubykaigi/game_server.rb', line 18

def queue
  @queue
end

Instance Method Details

#drainObject



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/road_to_rubykaigi/game_server.rb', line 20

def drain
  now = Time.now.to_f
  until @queue.empty?
    data = @queue.pop(true)
    t_ms = data['t']
    next if t_ms && now - t_ms.to_f / 1000.0 > MAX_AGE_SECONDS
    yield data
  end
rescue ThreadError
  # pop(true) raises if the queue empties mid-drain
end

#open_controllerObject



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/road_to_rubykaigi/game_server.rb', line 45

def open_controller
  url = "#{HOST}:#{PORT}/controller.html"
  command =
    case RbConfig::CONFIG['host_os']
    when /darwin/ then ['open', url]
    when /mswin|mingw|cygwin/ then ['cmd', '/c', 'start', '', url]
    else ['xdg-open', url]
    end
  pid = spawn(*command, out: File::NULL, err: File::NULL)
  Process.detach(pid)
rescue
  # best effort: don't crash the server if the browser can't be opened
end

#startObject



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/road_to_rubykaigi/game_server.rb', line 32

def start
  @queue.clear
  return if @server

  @server = build_server
  @thread = Thread.new { @server.start }
  at_exit do
    @server.shutdown rescue nil
    @thread.kill
  end
  open_controller unless Config.demo?
end