Class: Opi::Context

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, logger, route, request, response) ⇒ Context

Returns a new instance of Context.



6
7
8
9
10
11
12
13
# File 'lib/opi/context.rb', line 6

def initialize(env, logger, route, request, response)
  @env = env
  @logger = logger
  @route = route
  @request = request
  @response = response
  @error = nil
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



4
5
6
# File 'lib/opi/context.rb', line 4

def env
  @env
end

#errorObject (readonly)

Returns the value of attribute error.



4
5
6
# File 'lib/opi/context.rb', line 4

def error
  @error
end

#loggerObject (readonly)

Returns the value of attribute logger.



4
5
6
# File 'lib/opi/context.rb', line 4

def logger
  @logger
end

#requestObject (readonly)

Returns the value of attribute request.



4
5
6
# File 'lib/opi/context.rb', line 4

def request
  @request
end

#responseObject (readonly)

Returns the value of attribute response.



4
5
6
# File 'lib/opi/context.rb', line 4

def response
  @response
end

#routeObject (readonly)

Returns the value of attribute route.



4
5
6
# File 'lib/opi/context.rb', line 4

def route
  @route
end

Instance Method Details

#error!(message, status) ⇒ Object



19
20
21
# File 'lib/opi/context.rb', line 19

def error!(message, status)
  @error = {:message => message, :status => status}
end

#paramsObject



15
16
17
# File 'lib/opi/context.rb', line 15

def params
  {}.tap {|h| @request.params.each{|x| h[x.first.to_sym] = x.last}}
end

#runObject



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
56
57
58
59
60
61
62
63
64
65
# File 'lib/opi/context.rb', line 23

def run
  skip = route.options[:skip] || []
  skip = [skip] unless skip.is_a? Array

  route_before = route.options[:before] || []
  route_before = [route_before] unless route_before.is_a? Array

  (route.before + route_before).each do |before|
    next if skip.include? before

    self.send before # execute before filter

    if self.error
      response.body = ["{\"error\":\"#{error[:message]}\"}", "\n"]
      response.status = error[:status]
      return response
    end
  end

  # before filters must have succeeded
  action = instance_eval &route.block

  if action.respond_to? :success?
    if action.success?
      response.status = 200
      response.body = [action.result.to_json, "\n"]
    else
      response.status = 400
      response.body = [action.errors.symbolic.to_json, "\n"]
      logger.error "Reponse: #{action.errors.symbolic.to_json}".red
    end
  else
    response.status = 200
    response.body = [action.to_json, "\n"]
  end

  if self.error
    response.status = error[:status]
    response.body = [error[:message].to_json, "\n"]
  end

  response
end