Class: Cuttlebone::Drivers::Rack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/cuttlebone/drivers/rack.rb

Overview

Cuttlebone::Drivers::Rack::Middleware

It responds only to predefined HTTP POST calls and deals them according to Cuttlebone definitions and the associated driver’s internal state.

Instance Method Summary collapse

Constructor Details

#initialize(app, driver = nil) ⇒ Middleware

Returns a new instance of Middleware.



15
16
17
18
# File 'lib/cuttlebone/drivers/rack.rb', line 15

def initialize app, driver=nil
  @app    = app
  @driver = driver || Cuttlebone::Drivers::Rack.new
end

Instance Method Details

#call(env) ⇒ Object



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
50
51
52
53
54
55
# File 'lib/cuttlebone/drivers/rack.rb', line 20

def call env
  request = Rack::Request.new(env)

  return(@app.call(env)) unless request.post?
  return(@app.call(env)) unless request.path =~ %r{^/(?:(?:prompt|call)/([0-9a-f]{40}))|init$}
  # return(@app.call(env)) unless @request.is_json_request?

  response = Rack::Response.new
  response['Content-Type'] = 'application/json'

  results = { 'id' => nil, 'prompt' => nil }

  begin
    session = get_session_for(request.path)
    raise ArgumentError, "Cannot load cuttlebone-session!" unless session

    case request.path
    when '/init', %r{^/prompt/}
      results.merge! 'id' => session.id, 'prompt' => session.prompt
    when %r{^/call/}
      if command=request.params['command']
        _, _, output, error = session.call(command.force_encoding("UTF-8"))
        results.merge! 'id' => session.id, 'prompt' => session.prompt, 'output' => output, 'error' => error
      else
        response.status = 409
        results.merge! 'id' => session.id, 'prompt' => session.prompt, 'error' => 'No command was given!'
      end
    end
  rescue
    results.merge! 'id' => (session.id rescue nil), 'prompt' => (session.prompt rescue nil), 'error' => $!.message
  end

  response.write(results.to_json)

  return(response.finish)
end