module Grape::DSL::InsideRoute

Public Class Methods

post_filter_methods(type) click to toggle source

@param type [Symbol] The type of filter for which evaluation has been

completed

@return [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+.
# 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

Public Instance Methods

body(value = nil) click to toggle source

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

@example

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

GET /body # => "Body"
# File lib/grape/dsl/inside_route.rb, line 225
def body(value = nil)
  if value
    @body = value
  elsif value == false
    @body = ''
    status 204
  else
    @body
  end
end
content_type(val = nil) click to toggle source

Set response content-type

# File lib/grape/dsl/inside_route.rb, line 195
def content_type(val = nil)
  if val
    header(Grape::Http::Headers::CONTENT_TYPE, val)
  else
    header[Grape::Http::Headers::CONTENT_TYPE]
  end
end
cookies() click to toggle source

Set or get a cookie

@example

cookies[:mycookie] = 'mycookie val'
cookies['mycookie-string'] = 'mycookie string val'
cookies[:more] = { value: '123', expires: Time.at(0) }
cookies.delete :more
# File lib/grape/dsl/inside_route.rb, line 211
def cookies
  @cookies ||= Cookies.new
end
declared(*) click to toggle source

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.

@see +PostBeforeFilter#declared+

@param params [Hash] The initial hash to filter. Usually this will just be `params` @param options [Hash] Can pass `:include_missing`, `:stringify` and `:include_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.

# 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) click to toggle source

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. @param object [Object] the object to locate the Entity class for @param options [Hash] @option options :with [Class] the explicit entity class to use @return [Class] the located Entity class, or nil if none is found

# File lib/grape/dsl/inside_route.rb, line 355
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) click to toggle source

@return the representation of the given object as done through

the given entity_class.
# File lib/grape/dsl/inside_route.rb, line 378
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, headers = nil) click to toggle source

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

@param message [String] The message to display. @param status [Integer] the HTTP Status Code. Defaults to default_error_status, 500 if not set.

# File lib/grape/dsl/inside_route.rb, line 137
def error!(message, status = nil, headers = nil)
  self.status(status || namespace_inheritable(:default_error_status))
  throw :error, message: message, status: self.status, headers: headers
end
file(value = nil) click to toggle source

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

@example

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

GET /file # => "contents of file"
# File lib/grape/dsl/inside_route.rb, line 258
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) click to toggle source

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.

@example

get '/users/:id' do
  present User.find(params[:id]),
    with: API::Entities::User,
    admin: current_user.admin?
end
# File lib/grape/dsl/inside_route.rb, line 307
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) click to toggle source

Redirect to a new url.

@param url [String] The url to be redirect. @param options [Hash] The options used when redirect.

:permanent, default false.
:body, default a short message including the URL.
# File lib/grape/dsl/inside_route.rb, line 148
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_content() click to toggle source

Allows you to explicitly return no content.

@example

delete :id do
  return_no_content
  "not returned"
end

DELETE /12 # => 204 No Content, ""
# File lib/grape/dsl/inside_route.rb, line 245
def return_no_content
  status 204
  body false
end
route() click to toggle source

Returns route information for the current request.

@example

desc "Returns the route description."
get '/' do
  route.description
end
# File lib/grape/dsl/inside_route.rb, line 343
def route
  env[Grape::Env::GRAPE_ROUTING_ARGS][:route_info]
end
status(status = nil) click to toggle source

Set or retrieve the HTTP status code.

@param status [Integer] The HTTP Status Code to return for this request.

# File lib/grape/dsl/inside_route.rb, line 168
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) click to toggle source

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.

@example

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

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

See:

# File lib/grape/dsl/inside_route.rb, line 285
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
version() click to toggle source

The API version as specified in the URL.

# File lib/grape/dsl/inside_route.rb, line 128
def version
  env[Grape::Env::API_VERSION]
end