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, route, request, before, after) ⇒ Context

Returns a new instance of Context.



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

def initialize(env, route, request, before, after)
  @env = env
  @route = route
  @request = request
  @response = Response.new
  @before = before
  @after = after
  @error = nil
end

Instance Attribute Details

#afterObject (readonly)

Returns the value of attribute after.



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

def after
  @after
end

#beforeObject (readonly)

Returns the value of attribute before.



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

def before
  @before
end

#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

#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



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

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

#paramsObject



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

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

#runObject



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

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

  (self.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"]
    end
  else
    response.status = 200
    response.body = [action.to_json, "\n"]
  end

  response
end