Class: WebsocketGui::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/websocket-gui/base.rb

Constant Summary collapse

@@config =

class-level config, so you can wire your settings into your class These can also be provided when calling run!

{
	socket_port: 8080,
	socket_host: '127.0.0.1',
	http_port: 3000,
	http_host: '127.0.0.1',
	tick_interval: nil,
	view: :index,
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Base

Returns a new instance of Base.



25
26
27
# File 'lib/websocket-gui/base.rb', line 25

def initialize(config = {})
	@config = @@config.merge(config)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



23
24
25
# File 'lib/websocket-gui/base.rb', line 23

def config
  @config
end

Class Method Details

.method_missing(method, *args, &block) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/websocket-gui/base.rb', line 15

def self.method_missing(method, *args, &block)
	if block_given?
		@@config[method] = block
	else
		@@config[method] = args.first
	end
end

Instance Method Details

#run!(runtime_config = {}) ⇒ Object

start the socket server and the web server, and launch a browser to fetch the view from the web server



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/websocket-gui/base.rb', line 30

def run!(runtime_config = {})
	@config.merge! runtime_config

	EM.run do
		if @config[:tick_interval]
			EM.add_periodic_timer(@config[:tick_interval]) do
				socket_trigger(:on_tick, @socket_connected)
			end
		end

		EventMachine::WebSocket.run(host: @config[:socket_host], port: @config[:socket_port]) do |socket|
			@socket_active = socket
			socket.onopen do |handshake|
				@socket_connected = true
				socket_trigger(:on_socket_open, handshake)
			end

			socket.onmessage do |msg| 
				process_message(msg)
			end

			socket.onclose do 
				socket_trigger(:on_socket_close)
				@socket_connected = false 
			end
		end
	 
		Launchy.open("http://#{@config[:http_host]}:#{@config[:http_port]}/")
		WebsocketGui::SinatraWrapper.view_path = @config[:view]
		WebsocketGui::SinatraWrapper.run!(
			port: @config[:http_port], 
			bind: @config[:http_host])
	end
end

#socket_closeObject



69
70
71
# File 'lib/websocket-gui/base.rb', line 69

def socket_close
	@socket_active.stop if @socket_connected
end

#socket_send(msg) ⇒ Object



65
66
67
# File 'lib/websocket-gui/base.rb', line 65

def socket_send(msg)
	@socket_active.send msg if @socket_connected
end