Module: Grape::DSL::InsideRoute

Extended by:
ActiveSupport::Concern
Includes:
Headers, Settings
Included in:
Endpoint
Defined in:
lib/grape/dsl/inside_route.rb

Defined Under Namespace

Modules: PostBeforeFilter Classes: MethodNotYetAvailable

Instance Attribute Summary

Attributes included from Settings

#inheritable_setting, #top_level_setting

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Headers

#header

Methods included from Settings

#api_class_setting, #get_or_set, #global_setting, #namespace_end, #namespace_inheritable, #namespace_inheritable_to_nil, #namespace_reverse_stackable, #namespace_reverse_stackable_with_hash, #namespace_setting, #namespace_stackable, #namespace_stackable_with_hash, #namespace_start, #route_end, #route_setting, #unset, #unset_api_class_setting, #unset_global_setting, #unset_namespace_inheritable, #unset_namespace_setting, #unset_namespace_stackable, #unset_route_setting, #within_namespace

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.



21
22
23
24
# File 'lib/grape/dsl/inside_route.rb', line 21

def self.post_filter_methods(type)
  @post_filter_modules ||= { before: PostBeforeFilter }
  @post_filter_modules[type]
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"


231
232
233
234
235
236
237
238
239
240
# File 'lib/grape/dsl/inside_route.rb', line 231

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

#configurationObject



132
133
134
# File 'lib/grape/dsl/inside_route.rb', line 132

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

#content_type(val = nil) ⇒ Object

Set response content-type



201
202
203
204
205
206
207
# File 'lib/grape/dsl/inside_route.rb', line 201

def content_type(val = nil)
  if val
    header(Grape::Http::Headers::CONTENT_TYPE, val)
  else
    header[Grape::Http::Headers::CONTENT_TYPE]
  end
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


217
218
219
# File 'lib/grape/dsl/inside_route.rb', line 217

def cookies
  @cookies ||= Cookies.new
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+


123
124
125
# File 'lib/grape/dsl/inside_route.rb', line 123

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



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/grape/dsl/inside_route.rb', line 361

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

  if entity_class.nil?
    # entity class not explicitely 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

    object_class.ancestors.each do |potential|
      entity_class ||= (namespace_stackable_with_hash(:representations) || {})[potential]
    end

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

  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.



384
385
386
387
388
# File 'lib/grape/dsl/inside_route.rb', line 384

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

#error!(message, status = nil, additional_headers = 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.



142
143
144
145
146
# File 'lib/grape/dsl/inside_route.rb', line 142

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

#file(value = nil) ⇒ Object

Allows you to define the response as a file-like object.

Examples:

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

GET /file # => "contents of file"


264
265
266
267
268
269
270
271
272
273
274
# File 'lib/grape/dsl/inside_route.rb', line 264

def file(value = nil)
  if value.is_a?(String)
    file_body = Grape::ServeFile::FileBody.new(value)
    @file = Grape::ServeFile::FileResponse.new(file_body)
  elsif !value.is_a?(NilClass)
    warn '[DEPRECATION] Argument as FileStreamer-like object is deprecated. Use path to file instead.'
    @file = Grape::ServeFile::FileResponse.new(value)
  else
    @file
  end
end

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


313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/grape/dsl/inside_route.rb', line 313

def present(*args)
  options = args.count > 1 ? args.extract_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, **_options) ⇒ Object

Redirect to a new url.

Parameters:

  • url (String)

    The url to be redirect.

  • options (Hash)

    The options used when redirect. :permanent, default false. :body, default a short message including the URL.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/grape/dsl/inside_route.rb', line 154

def redirect(url, permanent: false, body: nil, **_options)
  body_message = body
  if permanent
    status 301
    body_message ||= "This resource has been moved permanently to #{url}."
  elsif env[Grape::Http::Headers::HTTP_VERSION] == 'HTTP/1.1' && request.request_method.to_s.upcase != Grape::Http::Headers::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, ""


251
252
253
254
# File 'lib/grape/dsl/inside_route.rb', line 251

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


349
350
351
# File 'lib/grape/dsl/inside_route.rb', line 349

def route
  env[Grape::Env::GRAPE_ROUTING_ARGS][:route_info]
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.



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/grape/dsl/inside_route.rb', line 174

def status(status = nil)
  case status
  when Symbol
    raise ArgumentError, "Status code :#{status} is invalid." unless Rack::Utils::SYMBOL_TO_STATUS_CODE.keys.include?(status)
    @status = Rack::Utils.status_code(status)
  when Integer
    @status = status
  when nil
    return @status if @status
    case request.request_method.to_s.upcase
    when Grape::Http::Headers::POST
      201
    when Grape::Http::Headers::DELETE
      if @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"


291
292
293
294
295
296
# File 'lib/grape/dsl/inside_route.rb', line 291

def stream(value = nil)
  header 'Content-Length', nil
  header 'Transfer-Encoding', nil
  header 'Cache-Control', 'no-cache' # Skips ETag generation (reading the response up front)
  file(value)
end

#versionObject

The API version as specified in the URL.



128
129
130
# File 'lib/grape/dsl/inside_route.rb', line 128

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