Class: Opi::API

Inherits:
Object
  • Object
show all
Defined in:
lib/opi/api.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.after(method) ⇒ Object



33
34
35
# File 'lib/opi/api.rb', line 33

def after(method)
  after_filters << method
end

.after_filtersObject



41
42
43
# File 'lib/opi/api.rb', line 41

def after_filters
  @after_filters ||= []
end

.before(method) ⇒ Object



29
30
31
# File 'lib/opi/api.rb', line 29

def before(method)
  before_filters << method
end

.before_filtersObject



37
38
39
# File 'lib/opi/api.rb', line 37

def before_filters
  @before_filters ||= []
end

.delete(path, options = {}, &block) ⇒ Object



20
21
22
# File 'lib/opi/api.rb', line 20

def delete(path, options={}, &block)
  route 'DELETE', path, options, block
end

.get(path, options = {}, &block) ⇒ Object



8
9
10
# File 'lib/opi/api.rb', line 8

def get(path, options={}, &block)
  route 'GET', path, options, block
end

.helpers(&block) ⇒ Object



49
50
51
52
53
# File 'lib/opi/api.rb', line 49

def helpers(&block)
  mod = Module.new
  mod.class_eval &block
  Context.send :include, mod
end

.post(path, options = {}, &block) ⇒ Object



12
13
14
# File 'lib/opi/api.rb', line 12

def post(path, options={}, &block)
  route 'POST', path, options, block
end

.put(path, &block) ⇒ Object



16
17
18
# File 'lib/opi/api.rb', line 16

def put(path, &block)
  route 'PUT', path, options, block
end

.route(method, path, options = {}, block) ⇒ Object



24
25
26
27
# File 'lib/opi/api.rb', line 24

def route(method, path, options={}, block)
  # TODO: remove&replace existing routes (on reload)
  router.routes.unshift({:method => method, :path => path, :options => options, :block => block})
end

.routerObject



45
46
47
# File 'lib/opi/api.rb', line 45

def router
  @router ||= Router.new
end

Instance Method Details

#call(env) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/opi/api.rb', line 57

def call(env)
  begin
    Loader.reload!

    request = Request.new(env)

    route, params = self.class.router.route(request.method, request.path)
    request.params.merge!(params) if params and params.is_a? Hash
    request.params.merge!('splat' => params.join(',')) if params and params.is_a? Array

    return [404, {'Content-Type' => 'application/json; charset=utf-8'}, ["{\"error\":\"404 Not Found\"}", "\n"]] unless route

    context = Context.new(env, route, request, self.class.before_filters, self.class.after_filters)
    response = context.run

    [response.status, response.header, response.body]
  rescue Exception => e
    return [500, {'Content-Type' => 'application/json; charset=utf-8'}, ["{\"error\":\"500 Internal Server Error\", \"message\":\"#{e.message}\"}", "\n"]]
  end
end