Module: Rave::Mixins::Controller

Includes:
Logger
Included in:
Rave::Models::Robot
Defined in:
lib/mixins/controller.rb

Instance Method Summary collapse

Methods included from Logger

#logger

Instance Method Details

#call(env) ⇒ Object



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
42
43
44
45
46
47
48
49
# File 'lib/mixins/controller.rb', line 7

def call(env)
  request = Rack::Request.new(env)
  path = request.path_info
  method = request.request_method
  logger.info("#{method}ing #{path}")
  begin
    #There are only 3 URLs that Wave can access: 
    #  robot capabilities, robot profile, and event notification
    if path == "/_wave/capabilities.xml" && method == "GET"
      [ 200, { 'Content-Type' => 'text/xml' }, capabilities_xml ]
    elsif path == "/_wave/robot/profile" && method == "GET"
      [ 200, { 'Content-Type' => 'application/json' }, profile_json ]
    elsif path == "/_wave/robot/jsonrpc" && method == "POST"
      body = request.body.read
      context, events = parse_json_body(body)
      events.each do |event|
        handle_event(event, context)
      end
      response = context.to_json
      logger.info("Structure (after):\n#{context.print_structure}")
      logger.info("Response:\n#{response}")
      [ 200, { 'Content-Type' => 'application/json' }, response ]
    elsif cron_job = @cron_jobs.find { |job| job[:path] == path }
      body = request.body.read
      context, events = parse_json_body(body)
      self.send(cron_job[:handler], context)
      [ 200, { 'Content-Type' => 'application/json' }, context.to_json ]
    elsif File.exist?(file = File.join(".", "public", *(path.split("/"))))
      #Static resource
      [ 200, { 'Content-Type' => static_resource_content_type(file) }, File.open(file) { |f| f.read } ]
    elsif self.respond_to?(:custom_routes)
      #Let the custom route method defined in the robot take care of the call
      self.custom_routes(request, path, method)
    else
      logger.warning("404 - Not Found: #{path}")
      [ 404, { 'Content-Type' => 'text/html' }, "404 - Not Found" ]
    end
  rescue Exception => e
    logger.warning("500 - Internal Server Error: #{path}")
    logger.warning("#{e.class}: #{e.message}\n\n#{e.backtrace.join("\n")}")
    [ 500, { 'Content-Type' => 'text/html' }, "500 - Internal Server Error"]
  end
end