Class: Mado::Server

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

Class Method Summary collapse

Class Method Details

.run(options) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mado/server.rb', line 3

def self.run(options)
  EM.kqueue = true if EM.kqueue?

  EM.run do
    sockets = []

    host = options[:host] || "0.0.0.0"
    port = options[:port] || "8080"
    debug = options[:debug] || false
    markdown_path = options[:markdown]

    EM.watch_file(markdown_path, Mado::FileHandler, sockets)

    EM::WebSocket.start(host: host, port: 8081, debug: debug) do |ws|
      ws.onopen do
        ws.send(Mado::Markdown.convert_markdown(markdown_path))
        sockets << ws unless sockets.include?(ws)
      end

      ws.onclose do
        sockets.delete(ws)
      end
    end

    app = Rack::Builder.app do
      Mado::App.set :environment, :production
      Mado::App.set :markdown_path, markdown_path

      map "/" do
        run Mado::App
      end
    end

    Rack::Server.start(app: app, Host: host, Port: port)

    trap("TERM") { EM.stop }
    trap("INT") { EM.stop }
  end
end