Class: DCell::Explorer

Inherits:
Reel::Server
  • Object
show all
Defined in:
lib/dcell/explorer.rb

Overview

Web UI for DCell TODO: rewrite this entire thing with less hax

Constant Summary collapse

ASSET_ROOT =
Pathname.new File.expand_path("../../../explorer", __FILE__)

Instance Method Summary collapse

Constructor Details

#initialize(host = "127.0.0.1", port = 7778) ⇒ Explorer

Returns a new instance of Explorer.



12
13
14
# File 'lib/dcell/explorer.rb', line 12

def initialize(host = "127.0.0.1", port = 7778)
  super(host, port, &method(:on_connection))
end

Instance Method Details

#node_path(node) ⇒ Object



70
71
72
# File 'lib/dcell/explorer.rb', line 70

def node_path(node)
  "/nodes/#{node.id}"
end

#on_connection(connection) ⇒ Object



16
17
18
19
20
# File 'lib/dcell/explorer.rb', line 16

def on_connection(connection)
  request = connection.request
  return unless request
  route connection, request
end

#render_resource(connection, path) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dcell/explorer.rb', line 38

def render_resource(connection, path)
  if node_id = path[%r{^nodes/(.*)$}, 1]
    node = DCell::Node[node_id]
    path = "index.html"
  else
    node = DCell.me
  end

  asset_path = ASSET_ROOT.join(path)
  if asset_path.exist?
    asset_path.open("r") do |file|
      connection.respond :ok, file
    end

    Logger.info "200 OK: /#{path}"
  elsif File.exist?(asset_path.to_s + ".erb") and node
    connection.respond :ok, render_template(asset_path.to_s + ".erb", node)
    Logger.info "200 OK: /#{path}"
  else
    connection.respond :not_found, "Not found"
    Logger.info "404 Not Found: /#{path}"
  end
end

#render_template(template, node) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/dcell/explorer.rb', line 62

def render_template(template, node)
  @node = node
  @info = @node[:info].to_hash

  template = ERB.new File.read(template, :mode => 'rb')
  template.result(binding)
end

#route(connection, request) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/dcell/explorer.rb', line 22

def route(connection, request)
  if request.url == "/"
    path = "index.html"
  else
    path = request.url[%r{^/([a-z0-9\.\-_]+(/[a-z0-9\.\-_]+)*)$}, 1]
  end

  if !path or path[".."]
    Logger.info "404 Not Found: #{request.path}"
    connection.respond :not_found, "Not found"
    return
  end

  render_resource connection, path
end