Class: Phaedra::RackApp

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

Instance Method Summary collapse

Constructor Details

#initialize(settings = {}) ⇒ RackApp

Returns a new instance of RackApp.



29
30
31
32
33
34
# File 'lib/phaedra/rack_app.rb', line 29

def initialize(settings = {})
  @settings = {
    "root_dir" => Dir.pwd,
    "serverless_api_dir" => "api"
  }.merge(settings)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/phaedra/rack_app.rb', line 36

def call(env)
  full_api_path = File.expand_path(@settings["serverless_api_dir"], @settings["root_dir"])
  base_api_folder = File.basename(full_api_path)
  req = Request.new(env)
  res = Rack::Response.new

  api_folder = File.dirname(req.path).sub("/#{base_api_folder}", "")
  endpoint = File.basename(req.path)
  ruby_path = File.join(full_api_path, api_folder, "#{endpoint}.rb")
  if File.exist?(ruby_path)
    if Object.constants.include?(:PhaedraFunction)
      Object.send(:remove_const, :PhaedraFunction)
    end
    load ruby_path
    
    func = PhaedraFunction.new
    func.service(req, res)

    output = res.finish
    unless output[2].respond_to?(:each)
      output[2] = Array(output[2])
    end

    output
  else
    raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
  end
rescue WEBrick::HTTPStatus::Status => e
  [e.code, { "Content-Type" => "text/plain" }, [e.reason_phrase]]
end