Class: Grape::Endpoint

Inherits:
Object
  • Object
show all
Includes:
DSL::InsideRoute
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.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DSL::InsideRoute

#body, #content_type, #cookies, #declared, #entity_class_for_obj, #error!, #header, #present, #redirect, #route, #status, #version

Constructor Details

#initialize(settings, options = {}, &block) ⇒ Endpoint

Returns a new instance of Endpoint.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/grape/endpoint.rb', line 49

def initialize(settings, options = {}, &block)
  require_option(options, :path)
  require_option(options, :method)

  @settings = settings
  @settings[:default_error_status] ||= 500

  @options = options

  @options[:path] = Array(options[:path])
  @options[:path] << '/' if options[:path].empty?

  @options[:method] = Array(options[:method])
  @options[:route_options] ||= {}

  if block_given?
    @source = block
    @block = self.class.generate_api_method(method_name, &block)
  end
end

Instance Attribute Details

#blockObject

Returns the value of attribute block.



7
8
9
# File 'lib/grape/endpoint.rb', line 7

def block
  @block
end

#envObject (readonly)

Returns the value of attribute env.



8
9
10
# File 'lib/grape/endpoint.rb', line 8

def env
  @env
end

#headersObject (readonly)

Returns the value of attribute headers.



8
9
10
# File 'lib/grape/endpoint.rb', line 8

def headers
  @headers
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/grape/endpoint.rb', line 7

def options
  @options
end

#paramsObject (readonly)

Returns the value of attribute params.



8
9
10
# File 'lib/grape/endpoint.rb', line 8

def params
  @params
end

#requestObject (readonly)

Returns the value of attribute request.



8
9
10
# File 'lib/grape/endpoint.rb', line 8

def request
  @request
end

#settingsObject

Returns the value of attribute settings.



7
8
9
# File 'lib/grape/endpoint.rb', line 7

def settings
  @settings
end

#sourceObject

Returns the value of attribute source.



7
8
9
# File 'lib/grape/endpoint.rb', line 7

def source
  @source
end

Class Method Details

.before_each(new_setup = false, &block) ⇒ Object



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

def before_each(new_setup = false, &block)
  if new_setup == false
    if block_given?
      @before_each = block
    else
      return @before_each
    end
  else
    @before_each = new_setup
  end
end

.generate_api_method(method_name, &block) ⇒ Proc

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Create an UnboundMethod that is appropriate for executing an endpoint route.

The unbound method allows explicit calls to +return+ without raising a +LocalJumpError+. The method will be removed, but a +Proc+ reference to it will be returned. The returned +Proc+ expects a single argument: the instance of +Endpoint+ to bind to the method during the call.

Parameters:

  • method_name (String, Symbol)

Returns:

  • (Proc)

Raises:

  • (NameError)

    an instance method with the same name already exists



38
39
40
41
42
43
44
45
46
# File 'lib/grape/endpoint.rb', line 38

def generate_api_method(method_name, &block)
  if instance_methods.include?(method_name.to_sym) || instance_methods.include?(method_name.to_s)
    raise NameError.new("method #{method_name.inspect} already exists and cannot be used as an unbound method name")
  end
  define_method(method_name, &block)
  method = instance_method(method_name)
  remove_method(method_name)
  proc { |endpoint_instance| method.bind(endpoint_instance).call }
end

Instance Method Details

#call(env) ⇒ Object



159
160
161
# File 'lib/grape/endpoint.rb', line 159

def call(env)
  dup.call!(env)
end

#call!(env) ⇒ Object



163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/grape/endpoint.rb', line 163

def call!(env)
  extend helpers

  env['api.endpoint'] = self
  if options[:app]
    options[:app].call(env)
  else
    builder = build_middleware
    builder.run options[:app] || lambda { |arg| run(arg) }
    builder.call(env)
  end
end

#compile_path(prepared_path, anchor = true, requirements = {}) ⇒ Object



152
153
154
155
156
157
# File 'lib/grape/endpoint.rb', line 152

def compile_path(prepared_path, anchor = true, requirements = {})
  endpoint_options = {}
  endpoint_options[:version] = /#{settings[:version].join('|')}/ if settings[:version]
  endpoint_options.merge!(requirements)
  Rack::Mount::Strexp.compile(prepared_path, endpoint_options, %w( / . ? ), anchor)
end

#endpointsObject

Return the collection of endpoints within this endpoint. This is the case when an Grape::API mounts another Grape::API.



178
179
180
181
182
183
184
# File 'lib/grape/endpoint.rb', line 178

def endpoints
  if options[:app] && options[:app].respond_to?(:endpoints)
    options[:app].endpoints
  else
    nil
  end
end

#method_nameObject



74
75
76
77
78
79
80
# File 'lib/grape/endpoint.rb', line 74

def method_name
  [options[:method],
   Namespace.joined_space(settings),
   settings.gather(:mount_path).join('/'),
   options[:path].join('/')
 ].join(" ")
end

#mount_in(route_set) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/grape/endpoint.rb', line 86

def mount_in(route_set)
  if endpoints
    endpoints.each { |e| e.mount_in(route_set) }
  else
    routes.each do |route|
      methods = [route.route_method]
      if !settings[:do_not_route_head] && route.route_method == "GET"
        methods << "HEAD"
      end
      methods.each do |method|
        route_set.add_route(self, {
                              path_info: route.route_compiled,
                              request_method: method
                            },  route_info: route)
      end
    end
  end
end

#namespaceObject



148
149
150
# File 'lib/grape/endpoint.rb', line 148

def namespace
  @namespace ||= Namespace.joined_space_path(settings)
end

#prepare_path(path) ⇒ Object



144
145
146
# File 'lib/grape/endpoint.rb', line 144

def prepare_path(path)
  Path.prepare(path, namespace, settings)
end

#prepare_routesObject



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/grape/endpoint.rb', line 105

def prepare_routes
  routes = []
  options[:method].each do |method|
    options[:path].each do |path|
      prepared_path = prepare_path(path)

      anchor = options[:route_options][:anchor]
      anchor = anchor.nil? ? true : anchor

      endpoint_requirements = options[:route_options][:requirements] || {}
      all_requirements = (settings.gather(:namespace).map(&:requirements) << endpoint_requirements)
      requirements = all_requirements.reduce({}) do |base_requirements, single_requirements|
        base_requirements.merge!(single_requirements)
      end

      path = compile_path(prepared_path, anchor && !options[:app], requirements)
      regex = Rack::Mount::RegexpWithNamedGroups.new(path)
      path_params = {}
      # named parameters in the api path
      named_params = regex.named_captures.map { |nc| nc[0] } - %w(version format)
      named_params.each { |named_param| path_params[named_param] = "" }
      # route parameters declared via desc or appended to the api declaration
      route_params = (options[:route_options][:params] || {})
      path_params.merge!(route_params)
      request_method = (method.to_s.upcase unless method == :any)
      routes << Route.new(options[:route_options].clone.merge(
        prefix: settings[:root_prefix],
        version: settings[:version] ? settings[:version].join('|') : nil,
        namespace: namespace,
        method: request_method,
        path: prepared_path,
        params: path_params,
        compiled: path
      ))
    end
  end
  routes
end

#require_option(options, key) ⇒ Object



70
71
72
# File 'lib/grape/endpoint.rb', line 70

def require_option(options, key)
  raise Grape::Exceptions::MissingOption.new(key) unless options.key?(key)
end

#routesObject



82
83
84
# File 'lib/grape/endpoint.rb', line 82

def routes
  @routes ||= endpoints ? endpoints.collect(&:routes).flatten : prepare_routes
end