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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Endpoint.

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/grape/endpoint.rb', line 39

def initialize(settings, options = {}, &block)
  @settings = settings
  if block_given?
    method_name = "#{options[:method]} #{settings.gather(:namespace).join( "/")} #{Array(options[:path]).join("/")}"
    @block = self.class.generate_api_method(method_name, &block)
  end
  @options = options

  raise ArgumentError, "Must specify :path option." unless options.key?(:path)
  options[:path] = Array(options[:path])
  options[:path] = ['/'] if options[:path].empty?

  raise ArgumentError, "Must specify :method option." unless options.key?(:method)
  options[:method] = Array(options[:method])

  options[:route_options] ||= {}
end

Instance Attribute Details

#blockObject

Returns the value of attribute block.



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

def block
  @block
end

#envObject (readonly)

Returns the value of attribute env.



12
13
14
# File 'lib/grape/endpoint.rb', line 12

def env
  @env
end

#optionsObject

Returns the value of attribute options.



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

def options
  @options
end

#requestObject (readonly)

Returns the value of attribute request.



12
13
14
# File 'lib/grape/endpoint.rb', line 12

def request
  @request
end

#settingsObject

Returns the value of attribute settings.



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

def settings
  @settings
end

Class Method Details

.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



28
29
30
31
32
33
34
35
36
# File 'lib/grape/endpoint.rb', line 28

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

#body(value = nil) ⇒ Object

Allows you to define the response body as something other than the return value.

Examples:

get '/body' do
  body "Body"
  "Not the Body"
end

GET /body # => "Body"


288
289
290
291
292
293
294
# File 'lib/grape/endpoint.rb', line 288

def body(value = nil)
  if value
    @body = value
  else
    @body
  end
end

#body_paramsObject

Pull out request body params if the content type matches and we’re on a POST or PUT



187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/grape/endpoint.rb', line 187

def body_params
  if ['POST', 'PUT'].include?(request.request_method.to_s.upcase) && request.content_length.to_i > 0
    return case env['CONTENT_TYPE']
      when 'application/json'
        MultiJson.decode(request.body.read)
      when 'application/xml'
        MultiXml.parse(request.body.read)
      else
        {}
      end
  end

  {}
end

#call(env) ⇒ Object



140
141
142
# File 'lib/grape/endpoint.rb', line 140

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

#call!(env) ⇒ Object



144
145
146
147
148
149
150
151
152
153
# File 'lib/grape/endpoint.rb', line 144

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

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



133
134
135
136
137
138
# File 'lib/grape/endpoint.rb', line 133

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

#content_type(val) ⇒ Object

Set response content-type



262
263
264
# File 'lib/grape/endpoint.rb', line 262

def content_type(val)
  header('Content-Type', val)
end

#cookiesObject

Set or get a cookie

Examples:

cookies[:mycookie] = 'mycookie val'
cookies['mycookie-string'] = 'mycookie string val'
cookies[:more] = { :value => '123', :expires => Time.at(0) }
cookies.delete :more


274
275
276
# File 'lib/grape/endpoint.rb', line 274

def cookies
  @cookies ||= Cookies.new
end

#declared(params, options = {}) ⇒ Object

A filtering method that will return a hash consisting only of keys that have been declared by a ‘params` statement.

Parameters:

  • params (Hash)

    The initial hash to filter. Usually this will just be ‘params`

  • options (Hash) (defaults to: {})

    Can pass ‘:include_missing` and `:stringify` options.



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/grape/endpoint.rb', line 170

def declared(params, options = {})
  options[:include_missing] = true unless options.key?(:include_missing)

  unless settings[:declared_params]
    raise ArgumentError, "Tried to filter for declared parameters but none exist."
  end

  settings[:declared_params].inject({}){|h,k|
    output_key = options[:stringify] ? k.to_s : k.to_sym
    if params.key?(output_key) || options[:include_missing]
      h[output_key] = params[k]
    end
    h
  }
end

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

End the request and display an error to the end user with the specified message.

Parameters:

  • message (String)

    The message to display.

  • status (Integer) (defaults to: 403)

    the HTTP Status Code. Defaults to 403.



210
211
212
# File 'lib/grape/endpoint.rb', line 210

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.



253
254
255
256
257
258
259
# File 'lib/grape/endpoint.rb', line 253

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

#mount_in(route_set) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/grape/endpoint.rb', line 61

def mount_in(route_set)
  if options[:app] && options[:app].respond_to?(:endpoints)
    options[:app].endpoints.each{|e| e.mount_in(route_set)}
  else
    routes.each do |route|
      route_set.add_route(self, {
        :path_info => route.route_compiled,
        :request_method => route.route_method,
      }, { :route_info => route })
    end
  end
end

#namespaceObject



129
130
131
# File 'lib/grape/endpoint.rb', line 129

def namespace
  Rack::Mount::Utils.normalize_path(settings.stack.map{|s| s[:namespace]}.join('/'))
end

#paramsObject

The parameters passed into the request as well as parsed from URL segments.



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

def params
  @params ||= Hashie::Mash.new.
    deep_merge(request.params).
    deep_merge(env['rack.routing_args'] || {}).
    deep_merge(self.body_params)
end

#prepare_path(path) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/grape/endpoint.rb', line 110

def prepare_path(path)
  parts = []
  parts << settings[:root_prefix] if settings[:root_prefix]

  uses_path_versioning = settings[:version] && settings[:version_options][:using] == :path
  namespace_is_empty = namespace && (namespace.to_s =~ /^\s*$/ || namespace.to_s == '/')
  path_is_empty = path && (path.to_s =~ /^\s*$/ || path.to_s == '/')

  parts << ':version' if uses_path_versioning
  if !uses_path_versioning || (!namespace_is_empty || !path_is_empty)
    parts << namespace.to_s if namespace
    parts << path.to_s if path && '/' != path
    format_suffix = '(.:format)'
  else
    format_suffix = '(/.:format)'
  end
  Rack::Mount::Utils.normalize_path(parts.join('/') + format_suffix)
end

#prepare_routesObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/grape/endpoint.rb', line 74

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

      requirements = options[:route_options][:requirements] || {}

      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] } - [ '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

#present(object, options = {}) ⇒ Object

Allows you to make use of Grape Entities by setting the response body to the serializable hash of the entity provided in the ‘:with` option. This has the added benefit of automatically passing along environment and version information to the serialization, making it very easy to do conditional exposures. See Entity docs for more info.

Examples:


get '/users/:id' do
  present User.find(params[:id]),
    :with => API::Entities::User,
    :admin => current_user.admin?
end


311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/grape/endpoint.rb', line 311

def present(object, options = {})
  entity_class = options.delete(:with)

  object.class.ancestors.each do |potential|
    entity_class ||= (settings[:representations] || {})[potential]
  end

  entity_class ||= object.class.const_get(:Entity) if object.class.const_defined?(:Entity)

  root = options.delete(:root)

  representation = if entity_class
    embeds = {:env => env}
    embeds[:version] = env['api.version'] if env['api.version']
    entity_class.represent(object, embeds.merge(options))
  else
    object
  end

  representation = { root => representation } if root
  body representation
end

#redirect(url, options = {}) ⇒ Object

Redirect to a new url.

Parameters:

  • url (String)

    The url to be redirect.

  • options (Hash) (defaults to: {})

    The options used when redirect. :permanent, default true.



219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/grape/endpoint.rb', line 219

def redirect(url, options = {})
  merged_options = {:permanent => false }.merge(options)
  if merged_options[:permanent]
    status 301
  else
    if env['HTTP_VERSION'] == 'HTTP/1.1' && request.request_method.to_s.upcase != "GET"
      status 303
    else
      status 302
    end
  end
  header "Location", url
  body ""
end

#routeObject

Returns route information for the current request.

Examples:


desc "Returns the route description."
get '/' do
  route.route_description
end


342
343
344
# File 'lib/grape/endpoint.rb', line 342

def route
  env["rack.routing_args"][:route_info]
end

#routesObject



57
58
59
# File 'lib/grape/endpoint.rb', line 57

def routes
  @routes ||= prepare_routes
end

#status(status = nil) ⇒ Object

Set or retrieve the HTTP status code.

Parameters:

  • status (Integer) (defaults to: nil)

    The HTTP Status Code to return for this request.



237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/grape/endpoint.rb', line 237

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

The API version as specified in the URL.



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

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