Class: Opi::API

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ API

Returns a new instance of API.



25
26
27
28
29
30
31
# File 'lib/opi/api.rb', line 25

def initialize(options={})
  puts "* Opi Version: #{Opi::VERSION} initializing".green
  @logger = options[:logger] || Logger.new(STDOUT)
  @logger.level = options[:debug] ? Logger::DEBUG : Logger::INFO
  @router = Router.new(self.class.root)
  @router.routes.collect{|x| @logger.debug "Route: #{x.method} #{x.path}"}
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



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

def logger
  @logger
end

Class Method Details

.helpers(&block) ⇒ Object



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

def helpers(&block)
  # TODO: allow argument to be a module
  mod = Module.new
  mod.class_eval &block
  Context.send :include, mod
end

.method_missing(method, *args, &block) ⇒ Object



10
11
12
# File 'lib/opi/api.rb', line 10

def method_missing(method, *args, &block)
  root.respond_to?(method) ? root.send(method, *args, &block) : super
end

.rootObject



6
7
8
# File 'lib/opi/api.rb', line 6

def root
  @root ||= Resource.new
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/opi/api.rb', line 33

def call(env)
  logger.debug env.inspect.cyan

  request = Request.new(env)
  response = Response.new

  begin
    Loader.reload!

    route, params = @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

    start_time = Time.now
    logger.info " Started #{request.method} \"#{request.path}\" for #{request.ip} at #{start_time.strftime('%d %b %H:%M')}"
    logger.info " Parameters: #{request.params}"

    if route
      logger.debug "#{request.method} #{request.path} => #{route.inspect}".green
      context = Context.new(env, logger, route, request, response)
      response = context.run
    else
      logger.debug "#{request.method} #{request.path} => route not found".red
      response.not_found!
    end

  rescue Exception => e
    logger.error "#{e.message.red}\n  #{e.backtrace[0..9].join("\n  ").yellow}"
    response.internal_server_error!(e)
  end

  logger.info " Completed #{response.status} in #{((Time.now - start_time)*1000).round(2)}ms"
  [response.status, response.header, response.body]
end