Module: Grape::DSL::InsideRoute

Included in:
Endpoint
Defined in:
lib/grape/dsl/inside_route.rb

Defined Under Namespace

Modules: PostBeforeFilter Classes: MethodNotYetAvailable

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.post_filter_methods(type) ⇒ Module

Returns A module containing method overrides suitable for the position in the filter evaluation sequence denoted by type. This defaults to an empty module if no overrides are defined for the given filter type.

Parameters:

  • type (Symbol)

    The type of filter for which evaluation has been completed

Returns:

  • (Module)

    A module containing method overrides suitable for the position in the filter evaluation sequence denoted by type. This defaults to an empty module if no overrides are defined for the given filter type.



16
17
18
19
# File 'lib/grape/dsl/inside_route.rb', line 16

def self.post_filter_methods(type)
  @post_filter_modules ||= { before: PostBeforeFilter }
  @post_filter_modules[type]
end

Instance Method Details

#api_format(format) ⇒ Object



422
423
424
# File 'lib/grape/dsl/inside_route.rb', line 422

def api_format(format)
  env[Grape::Env::API_FORMAT] = format
end

#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"


248
249
250
251
252
253
254
255
256
257
# File 'lib/grape/dsl/inside_route.rb', line 248

def body(value = nil)
  if value
    @body = value
  elsif value == false
    @body = ''
    status 204
  else
    instance_variable_defined?(:@body) ? @body : nil
  end
end

#configurationObject



154
155
156
# File 'lib/grape/dsl/inside_route.rb', line 154

def configuration
  options[:for].configuration.evaluate
end

#content_type(val = nil) ⇒ Object

Set response content-type



230
231
232
233
234
235
236
# File 'lib/grape/dsl/inside_route.rb', line 230

def content_type(val = nil)
  if val
    header(Rack::CONTENT_TYPE, val)
  else
    header[Rack::CONTENT_TYPE]
  end
end

#contextObject



426
427
428
# File 'lib/grape/dsl/inside_route.rb', line 426

def context
  self
end

#declaredObject

A filtering method that will return a hash consisting only of keys that have been declared by a ‘params` statement against the current/target endpoint or parent namespaces.

options. ‘:include_parent_namespaces` defaults to true, hence must be set to false if you want only to return params declared against the current/target endpoint.

Parameters:

  • params (Hash)

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

  • options (Hash)

    Can pass ‘:include_missing`, `:stringify` and `:include_parent_namespaces`

Raises:

See Also:

  • Grape::DSL::InsideRoute.+PostBeforeFilter+PostBeforeFilter#declared+


145
146
147
# File 'lib/grape/dsl/inside_route.rb', line 145

def declared(*)
  raise MethodNotYetAvailable, '#declared is not available prior to parameter validation.'
end

#entity_class_for_obj(object, options) ⇒ Class

Attempt to locate the Entity class for a given object, if not given explicitly. This is done by looking for the presence of Klass::Entity, where Klass is the class of the ‘object` parameter, or one of its ancestors.

Parameters:

  • object (Object)

    the object to locate the Entity class for

  • options (Hash)

Options Hash (options):

  • :with (Class)

    the explicit entity class to use

Returns:

  • (Class)

    the located Entity class, or nil if none is found



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/grape/dsl/inside_route.rb', line 389

def entity_class_for_obj(object, options)
  entity_class = options.delete(:with)
  return entity_class if entity_class

  # entity class not explicitly defined, auto-detect from relation#klass or first object in the collection
  object_class = if object.respond_to?(:klass)
                   object.klass
                 else
                   object.respond_to?(:first) ? object.first.class : object.class
                 end

  representations = inheritable_setting.namespace_stackable_with_hash(:representations)
  if representations
    potential = object_class.ancestors.detect { |potential| representations.key?(potential) }
    entity_class = representations[potential] if potential
  end

  entity_class = object_class.const_get(:Entity) if !entity_class && object_class.const_defined?(:Entity) && object_class.const_get(:Entity).respond_to?(:represent)
  entity_class
end

#entity_representation_for(entity_class, object, options) ⇒ Object

Returns the representation of the given object as done through the given entity_class.

Returns:

  • the representation of the given object as done through the given entity_class.



412
413
414
415
416
# File 'lib/grape/dsl/inside_route.rb', line 412

def entity_representation_for(entity_class, object, options)
  embeds = { env: env }
  embeds[:version] = env[Grape::Env::API_VERSION] if env.key?(Grape::Env::API_VERSION)
  entity_class.represent(object, **embeds, **options)
end

#error!(message, status = nil, additional_headers = nil, backtrace = nil, original_exception = nil) ⇒ 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: nil)

    The HTTP Status Code. Defaults to default_error_status, 500 if not set.

  • additional_headers (Hash) (defaults to: nil)

    Addtional headers for the response.

  • backtrace (Array<String>) (defaults to: nil)

    The backtrace of the exception that caused the error.

  • original_exception (Exception) (defaults to: nil)

    The original exception that caused the error.



166
167
168
169
170
171
172
173
174
175
# File 'lib/grape/dsl/inside_route.rb', line 166

def error!(message, status = nil, additional_headers = nil, backtrace = nil, original_exception = nil)
  status = self.status(status || inheritable_setting.namespace_inheritable[:default_error_status])
  headers = additional_headers.present? ? header.merge(additional_headers) : header
  throw :error,
        message: message,
        status: status,
        headers: headers,
        backtrace: backtrace,
        original_exception: original_exception
end

#http_versionObject



418
419
420
# File 'lib/grape/dsl/inside_route.rb', line 418

def http_version
  env.fetch('HTTP_VERSION') { env[Rack::SERVER_PROTOCOL] }
end

#present(*args, **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


340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/grape/dsl/inside_route.rb', line 340

def present(*args, **options)
  key, object = if args.count == 2 && args.first.is_a?(Symbol)
                  args
                else
                  [nil, args.first]
                end
  entity_class = entity_class_for_obj(object, options)

  root = options.delete(:root)

  representation = if entity_class
                     entity_representation_for(entity_class, object, options)
                   else
                     object
                   end

  representation = { root => representation } if root

  if key
    representation = (body || {}).merge(key => representation)
  elsif entity_class.present? && body
    raise ArgumentError, "Representation of type #{representation.class} cannot be merged." unless representation.respond_to?(:merge)

    representation = body.merge(representation)
  end

  body representation
end

#redirect(url, permanent: false, body: nil) ⇒ Object

Redirect to a new url.

Parameters:

  • url (String)

    The url to be redirect.

  • permanent (Boolean) (defaults to: false)

    default false.

  • body (defaults to: nil)

    default a short message including the URL.



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/grape/dsl/inside_route.rb', line 182

def redirect(url, permanent: false, body: nil)
  body_message = body
  if permanent
    status 301
    body_message ||= "This resource has been moved permanently to #{url}."
  elsif http_version == 'HTTP/1.1' && !request.get?
    status 303
    body_message ||= "An alternate resource is located at #{url}."
  else
    status 302
    body_message ||= "This resource has been moved temporarily to #{url}."
  end
  header 'Location', url
  content_type 'text/plain'
  body body_message
end

#return_no_contentObject

Allows you to explicitly return no content.

Examples:

delete :id do
  return_no_content
  "not returned"
end

DELETE /12 # => 204 No Content, ""


268
269
270
271
# File 'lib/grape/dsl/inside_route.rb', line 268

def return_no_content
  status 204
  body false
end

#routeObject

Returns route information for the current request.

Examples:


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


377
378
379
# File 'lib/grape/dsl/inside_route.rb', line 377

def route
  env[Grape::Env::GRAPE_ROUTING_ARGS][:route_info]
end

#sendfile(value = nil) ⇒ Object

Allows you to send a file to the client via sendfile.

Examples:

get '/file' do
  sendfile FileStreamer.new(...)
end

GET /file # => "contents of file"


281
282
283
284
285
286
287
288
289
290
# File 'lib/grape/dsl/inside_route.rb', line 281

def sendfile(value = nil)
  if value.is_a?(String)
    file_body = Grape::ServeStream::FileBody.new(value)
    @stream = Grape::ServeStream::StreamResponse.new(file_body)
  elsif !value.is_a?(NilClass)
    raise ArgumentError, 'Argument must be a file path'
  else
    stream
  end
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.



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/grape/dsl/inside_route.rb', line 202

def status(status = nil)
  case status
  when Symbol
    raise ArgumentError, "Status code :#{status} is invalid." unless Rack::Utils::SYMBOL_TO_STATUS_CODE.key?(status)

    @status = Rack::Utils.status_code(status)
  when Integer
    @status = status
  when nil
    return @status if instance_variable_defined?(:@status) && @status

    if request.post?
      201
    elsif request.delete?
      if instance_variable_defined?(:@body) && @body.present?
        200
      else
        204
      end
    else
      200
    end
  else
    raise ArgumentError, 'Status code must be Integer or Symbol.'
  end
end

#stream(value = nil) ⇒ Object

Allows you to define the response as a streamable object.

If Content-Length and Transfer-Encoding are blank (among other conditions), Rack assumes this response can be streamed in chunks.

See:

Examples:

get '/stream' do
  stream FileStreamer.new(...)
end

GET /stream # => "chunked contents of file"


307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/grape/dsl/inside_route.rb', line 307

def stream(value = nil)
  return if value.nil? && @stream.nil?

  header Rack::CONTENT_LENGTH, nil
  header 'Transfer-Encoding', nil
  header Rack::CACHE_CONTROL, 'no-cache' # Skips ETag generation (reading the response up front)
  if value.is_a?(String)
    file_body = Grape::ServeStream::FileBody.new(value)
    @stream = Grape::ServeStream::StreamResponse.new(file_body)
  elsif value.respond_to?(:each)
    @stream = Grape::ServeStream::StreamResponse.new(value)
  elsif !value.is_a?(NilClass)
    raise ArgumentError, 'Stream object must respond to :each.'
  else
    @stream
  end
end

#versionObject

The API version as specified in the URL.



150
151
152
# File 'lib/grape/dsl/inside_route.rb', line 150

def version
  env[Grape::Env::API_VERSION]
end