Class: Dasht::RackApp

Inherits:
Object
  • Object
show all
Defined in:
lib/dasht/rack_app.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent) ⇒ RackApp

Returns a new instance of RackApp.



5
6
7
# File 'lib/dasht/rack_app.rb', line 5

def initialize(parent)
  @parent = parent
end

Instance Attribute Details

#parentObject

Returns the value of attribute parent.



3
4
5
# File 'lib/dasht/rack_app.rb', line 3

def parent
  @parent
end

Instance Method Details

#_call(env) ⇒ Object



29
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
64
65
66
67
68
69
70
71
72
# File 'lib/dasht/rack_app.rb', line 29

def _call(env)
  if "/" == env["REQUEST_PATH"] && parent.boards["default"]
    return ['200', {'Content-Type' => 'text/html'}, [parent.boards["default"].to_html]]
  end

  /^\/boards\/(.+)$/.match(env["REQUEST_PATH"]) do |match|
    board = match[1]
    if parent.boards[board]
      return ['200', {'Content-Type' => 'text/html'}, [parent.boards[board].to_html]]
    else
      return ['404', {'Content-Type' => 'text/html'}, ["Board #{board} not found."]]
    end
  end

  /^\/data$/.match(env["REQUEST_PATH"]) do |match|
    queries = JSON.parse(env['rack.input'].gets)
    now = Time.now.to_i
    data = queries.map do |query|
      metric     = query["metric"]
      resolution = query["resolution"]
      periods    = query["periods"]
      ts = now - (resolution * periods)
      (1..periods).map do |n|
        parent.metrics.get(metric, ts, ts += resolution) || 0
      end
    end

    return ['200', {'Content-Type' => 'application/json'}, [data.to_json]]
  end

  /^\/data\/(.+)/.match(env["REQUEST_PATH"]) do |match|
    parts = match[1].split('/')
    metric     = parts.shift
    resolution = parts.shift.to_i
    periods    = (parts.shift || 1).to_i
    ts = Time.now.to_i - (resolution * periods)
    data = (1..periods).map do |n|
      parent.metrics.get(metric, ts, ts += resolution) || 0
    end
    return ['200', {'Content-Type' => 'application/json'}, [data.to_json]]
  end

  return ['404', {'Content-Type' => 'text/html'}, ["Path not found: #{env['REQUEST_PATH']}"]]
end

#root_pathObject



9
10
11
# File 'lib/dasht/rack_app.rb', line 9

def root_path
  File.join(File.dirname(__FILE__), "..", "..")
end

#run(port) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/dasht/rack_app.rb', line 13

def run(port)
  context = self
  app = Rack::Builder.new do
    use Rack::Static, :urls => ["/assets"], :root  => context.root_path
    run lambda { |env|
      begin
        context._call(env)
      rescue => e
        context.parent.log e
        raise e
      end
    }
  end
  Rack::Server.start(:app => app, :Port => (port || 8080))
end