Class: Grape::Endpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/endpoint.rb

Overview

An Endpoint is the proxy scope in which all routing blocks are executed. In other words, any methods on the instance level of this class may be called from inside a ‘get`, `post`, etc. block.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Endpoint

Returns a new instance of Endpoint.



10
11
12
# File 'lib/grape/endpoint.rb', line 10

def initialize(&block)
  @block = block
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



14
15
16
# File 'lib/grape/endpoint.rb', line 14

def env
  @env
end

#requestObject (readonly)

Returns the value of attribute request.



14
15
16
# File 'lib/grape/endpoint.rb', line 14

def request
  @request
end

Instance Method Details

#call(env) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/grape/endpoint.rb', line 55

def call(env)
  @env = env
  @request = Rack::Request.new(@env)
  @header = {}
  
  response_text = instance_eval &@block
  
  [status, header, [response_text]]
end

#error!(message, status = 403) ⇒ Object



26
27
28
# File 'lib/grape/endpoint.rb', line 26

def error!(message, status=403)
  throw :error, :message => message, :status => status
end

#header(key = nil, val = nil) ⇒ Object

Set an individual header or retrieve all headers that have been set.



47
48
49
50
51
52
53
# File 'lib/grape/endpoint.rb', line 47

def header(key = nil, val = nil)
  if key
    val ? @header[key.to_s] = val : @header.delete(key.to_s)
  else
    @header
  end
end

#paramsObject



16
17
18
19
20
21
22
# File 'lib/grape/endpoint.rb', line 16

def params
  @params ||= request.params.merge(env['rack.routing_args'] || {}).inject({}) do |h,(k,v)|
    h[k.to_s] = v
    h[k.to_sym] = v
    h
  end
end

#status(status = nil) ⇒ Object

Set or retrieve the HTTP status code.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/grape/endpoint.rb', line 31

def status(status = nil)
  if status
    @status = status
  else
    return @status if @status
    case request.request_method.to_s.upcase
      when 'POST'
        201
      else
        200
    end
  end        
end

#versionObject



24
# File 'lib/grape/endpoint.rb', line 24

def version; env['api.version'] end