Module: Grape::DSL::InsideRoute

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

Instance Attribute Summary

Attributes included from Settings

#inheritable_setting, #top_level_setting

Instance Method Summary collapse

Methods included from Settings

#api_class_setting, #get_or_set, #global_setting, #namespace_end, #namespace_inheritable, #namespace_inheritable_to_nil, #namespace_setting, #namespace_stackable, #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

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"


159
160
161
162
163
164
165
166
167
168
# File 'lib/grape/dsl/inside_route.rb', line 159

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

#content_type(val = nil) ⇒ Object

Set response content-type



129
130
131
132
133
134
135
# File 'lib/grape/dsl/inside_route.rb', line 129

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


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

def cookies
  @cookies ||= Cookies.new
end

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

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) (defaults to: {})

    Can pass :include_missing, :stringify and :include_parent_namespaces



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/grape/dsl/inside_route.rb', line 18

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

  if declared_params.nil?
    declared_params = (!options[:include_parent_namespaces] ? route_setting(:declared_params) :
        (route_setting(:saved_declared_params) || [])).flatten(1) || []
  end

  unless declared_params
    fail ArgumentError, 'Tried to filter for declared parameters but none exist.'
  end

  if params.is_a? Array
    params.map do |param|
      declared(param || {}, options, declared_params)
    end
  else
    declared_params.inject(Hashie::Mash.new) do |hash, key|
      key = { key => nil } unless key.is_a? Hash

      key.each_pair do |parent, children|
        output_key = options[:stringify] ? parent.to_s : parent.to_sym

        next unless options[:include_missing] || params.key?(parent)

        hash[output_key] = if children
                             children_params = params[parent] || (children.is_a?(Array) ? [] : {})
                             declared(children_params, options, Array(children))
                           else
                             params[parent]
                           end
      end

      hash
    end
  end
end

#entity_class_for_obj(object, options) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/grape/dsl/inside_route.rb', line 241

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 ||= (Grape::DSL::Configuration.stacked_hash_to_hash(namespace_stackable(: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



262
263
264
265
266
# File 'lib/grape/dsl/inside_route.rb', line 262

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

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



67
68
69
70
# File 'lib/grape/dsl/inside_route.rb', line 67

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) ⇒ 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"


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

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

#header(key = nil, val = nil) ⇒ Object

Set an individual header or retrieve all headers that have been set.



120
121
122
123
124
125
126
# File 'lib/grape/dsl/inside_route.rb', line 120

def header(key = nil, val = nil)
  if key
    val ? @header[key.to_s] = val : @header.delete(key.to_s)
  else
    @header
  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


201
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 201

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
    fail ArgumentError, "Representation of type #{representation.class} cannot be merged." unless representation.respond_to?('merge')
    representation = @body.merge(representation)
  end

  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 false.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/grape/dsl/inside_route.rb', line 77

def redirect(url, options = {})
  merged_options = { permanent: false }.merge(options)
  if merged_options[:permanent]
    status 301
  else
    if env[Grape::Http::Headers::HTTP_VERSION] == 'HTTP/1.1' && request.request_method.to_s.upcase != Grape::Http::Headers::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


237
238
239
# File 'lib/grape/dsl/inside_route.rb', line 237

def route
  env['rack.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.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/grape/dsl/inside_route.rb', line 95

def status(status = nil)
  case status
  when Symbol
    if Rack::Utils::SYMBOL_TO_STATUS_CODE.keys.include?(status)
      @status = Rack::Utils.status_code(status)
    else
      fail ArgumentError, "Status code :#{status} is invalid."
    end
  when Fixnum
    @status = status
  when nil
    return @status if @status
    case request.request_method.to_s.upcase
    when Grape::Http::Headers::POST
      201
    else
      200
    end
  else
    fail ArgumentError, 'Status code must be Fixnum or Symbol.'
  end
end

#versionObject

The API version as specified in the URL.



58
59
60
# File 'lib/grape/dsl/inside_route.rb', line 58

def version
  env['api.version']
end