Module: Grape::DSL::Parameters

Extended by:
ActiveSupport::Concern
Included in:
Validations::ParamsScope
Defined in:
lib/grape/dsl/parameters.rb

Overview

Defines DSL methods, meant to be applied to a ParamsScope, which define and describe the parameters accepted by an endpoint, or all endpoints within a namespace.

Defined Under Namespace

Classes: EmptyOptionalValue

Instance Method Summary collapse

Instance Method Details

#all_or_none_of(*attrs) ⇒ Object

Require that either all given params are present, or none are.

Parameters:

  • attrs (*Symbol)

    parameters to validate



197
198
199
# File 'lib/grape/dsl/parameters.rb', line 197

def all_or_none_of(*attrs)
  validates(attrs, all_or_none_of: { value: true, message: extract_message_option(attrs) })
end

#at_least_one_of(*attrs) ⇒ Object

Require at least one of the given parameters to be present.

Parameters:

  • attrs (*Symbol)

    parameters to validate



191
192
193
# File 'lib/grape/dsl/parameters.rb', line 191

def at_least_one_of(*attrs)
  validates(attrs, at_least_one_of: { value: true, message: extract_message_option(attrs) })
end

#build_with(build_with = nil) ⇒ Object

Set the module used to build the request.params.

Examples:


require 'grape/extenstions/hashie_mash'
class API < Grape::API
  desc "Get collection"
  params do
    build_with Grape::Extensions::Hashie::Mash::ParamBuilder
    requires :user_id, type: Integer
  end
  get do
    params['user_id']
  end
end

Parameters:

  • build_with (defaults to: nil)

    the ParamBuilder module to use when building request.params Available builders are:

    * Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder (default)
    * Grape::Extensions::Hash::ParamBuilder
    * Grape::Extensions::Hashie::Mash::ParamBuilder
    


33
34
35
# File 'lib/grape/dsl/parameters.rb', line 33

def build_with(build_with = nil)
  @api.namespace_inheritable(:build_params_with, build_with)
end

#declared_param?(param) ⇒ Boolean

Test for whether a certain parameter has been defined in this params block yet.

Returns:

  • (Boolean)

    whether the parameter has been defined



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

def declared_param?(param)
  if lateral?
    # Elements of @declared_params of lateral scope are pushed in @parent. So check them in @parent.
    @parent.declared_param?(param)
  else
    # @declared_params also includes hashes of options and such, but those
    # won't be flattened out.
    @declared_params.flatten.any? do |declared_param_attr|
      first_hash_key_or_param(declared_param_attr.key) == param
    end
  end
end

#exactly_one_of(*attrs) ⇒ Object

Require exactly one of the given parameters to be present.

Parameters:

  • attrs (*Symbol)

    parameters to validate



185
186
187
# File 'lib/grape/dsl/parameters.rb', line 185

def exactly_one_of(*attrs)
  validates(attrs, exactly_one_of: { value: true, message: extract_message_option(attrs) })
end

#given(*attrs) { ... } ⇒ Object

Define a block of validations which should be applied if and only if the given parameter is present. The parameters are not nested.

Parameters:

  • attr (Symbol)

    the parameter which, if present, triggers the validations

Yields:

  • a parameter definition DSL

Raises:

  • Grape::Exceptions::UnknownParameter if ‘attr` has not been defined in this scope yet



208
209
210
211
212
213
214
# File 'lib/grape/dsl/parameters.rb', line 208

def given(*attrs, &block)
  attrs.each do |attr|
    proxy_attr = first_hash_key_or_param(attr)
    raise Grape::Exceptions::UnknownParameter.new(proxy_attr) unless declared_param?(proxy_attr)
  end
  new_lateral_scope(dependent_on: attrs, &block)
end

#map_params(params, element, is_array = false) ⇒ Object



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

def map_params(params, element, is_array = false)
  if params.is_a?(Array)
    params.map do |el|
      map_params(el, element, true)
    end
  elsif params.is_a?(Hash)
    params[element] || (@optional && is_array ? EmptyOptionalValue : {})
  elsif params == EmptyOptionalValue
    EmptyOptionalValue
  else
    {}
  end
end

#mutually_exclusive(*attrs) ⇒ Object

Disallow the given parameters to be present in the same request.

Parameters:

  • attrs (*Symbol)

    parameters to validate



179
180
181
# File 'lib/grape/dsl/parameters.rb', line 179

def mutually_exclusive(*attrs)
  validates(attrs, mutual_exclusion: { value: true, message: extract_message_option(attrs) })
end

#optional(*attrs, &block) ⇒ Object

Allow, but don’t require, one or more parameters for the current

endpoint.

Parameters:

  • attrs

    list of parameters names, or, if :using is passed as an option, which keys to include (:all or :none) from the :using hash. The last key can be a hash, which specifies options for the parameters

Options Hash (*attrs):

  • :type (Class)

    the type to coerce this parameter to before passing it to the endpoint. See Validations::Types for a list of types that are supported automatically. Custom classes may be used where they define a class-level ‘::parse` method, or in conjunction with the `:coerce_with` parameter. `JSON` may be supplied to denote `JSON`-formatted objects or arrays of objects. `Array` accepts the same values as `JSON` but will wrap single objects in an `Array`.

  • :types (Array<Class>)

    may be supplied in place of :type to declare an attribute that has multiple allowed types. See Validations::Types::MultipleTypeCoercer for more details on coercion and validation rules for variant-type parameters.

  • :desc (String)

    description to document this parameter

  • :default (Object)

    default value, if parameter is optional

  • :values (Array)

    permissable values for this field. If any other value is given, it will be handled as a validation error

  • :using (Hash[Symbol => Hash])

    a hash defining keys and options, like that returned by Entity#documentation. The value of each key is an options hash accepting the same parameters

  • :except (Array[Symbol])

    a list of keys to exclude from the :using Hash. The meaning of this depends on if :all or :none was passed; :all + :except will make the :except fields optional, whereas :none + :except will make the :except fields required

  • :coerce_with (#parse, #call)

    method to be used when coercing the parameter to the type named by ‘attrs`. Any class or object that defines `::parse` or `::call` may be used.



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/grape/dsl/parameters.rb', line 147

def optional(*attrs, &block)
  orig_attrs = attrs.clone

  opts = attrs.extract_options!.clone
  type = opts[:type]
  opts = @group.deep_merge(opts) if instance_variable_defined?(:@group) && @group

  # check type for optional parameter group
  if attrs && block
    raise Grape::Exceptions::MissingGroupType if type.nil?
    raise Grape::Exceptions::UnsupportedGroupType unless Grape::Validations::Types.group?(type)
  end

  if opts[:using]
    require_optional_fields(attrs.first, opts)
  else
    validate_attributes(attrs, opts, &block)

    block ? new_scope(orig_attrs, true, &block) : push_declared_params(attrs, **opts.slice(:as))
  end
end

#params(params) ⇒ Object

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.

Returns hash of parameters relevant for the current scope.

Parameters:

  • params (Hash)

    initial hash of parameters

Returns:

  • hash of parameters relevant for the current scope



253
254
255
256
257
# File 'lib/grape/dsl/parameters.rb', line 253

def params(params)
  params = @parent.params(params) if instance_variable_defined?(:@parent) && @parent
  params = map_params(params, @element) if instance_variable_defined?(:@element) && @element
  params
end

#requires(*attrs, &block) ⇒ Object Also known as: group

Require one or more parameters for the current endpoint.

Examples:


params do
  # Basic usage: require a parameter of a certain type
  requires :user_id, type: Integer

  # You don't need to specify type; String is default
  requires :foo

  # Multiple params can be specified at once if they share
  # the same options.
  requires :x, :y, :z, type: Date

  # Nested parameters can be handled as hashes. You must
  # pass in a block, within which you can use any of the
  # parameters DSL methods.
  requires :user, type: Hash do
    requires :name, type: String
  end
end

Parameters:

  • attrs

    list of parameters names, or, if :using is passed as an option, which keys to include (:all or :none) from the :using hash. The last key can be a hash, which specifies options for the parameters

Options Hash (*attrs):

  • :type (Class)

    the type to coerce this parameter to before passing it to the endpoint. See Validations::Types for a list of types that are supported automatically. Custom classes may be used where they define a class-level ‘::parse` method, or in conjunction with the `:coerce_with` parameter. `JSON` may be supplied to denote `JSON`-formatted objects or arrays of objects. `Array` accepts the same values as `JSON` but will wrap single objects in an `Array`.

  • :types (Array<Class>)

    may be supplied in place of :type to declare an attribute that has multiple allowed types. See Validations::Types::MultipleTypeCoercer for more details on coercion and validation rules for variant-type parameters.

  • :desc (String)

    description to document this parameter

  • :default (Object)

    default value, if parameter is optional

  • :values (Array)

    permissable values for this field. If any other value is given, it will be handled as a validation error

  • :using (Hash[Symbol => Hash])

    a hash defining keys and options, like that returned by Entity#documentation. The value of each key is an options hash accepting the same parameters

  • :except (Array[Symbol])

    a list of keys to exclude from the :using Hash. The meaning of this depends on if :all or :none was passed; :all + :except will make the :except fields optional, whereas :none + :except will make the :except fields required

  • :coerce_with (#parse, #call)

    method to be used when coercing the parameter to the type named by ‘attrs`. Any class or object that defines `::parse` or `::call` may be used.



128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/grape/dsl/parameters.rb', line 128

def requires(*attrs, &block)
  orig_attrs = attrs.clone

  opts = attrs.extract_options!.clone
  opts[:presence] = { value: true, message: opts[:message] }
  opts = @group.deep_merge(opts) if instance_variable_defined?(:@group) && @group

  if opts[:using]
    require_required_and_optional_fields(attrs.first, opts)
  else
    validate_attributes(attrs, opts, &block)
    block ? new_scope(orig_attrs, &block) : push_declared_params(attrs, **opts.slice(:as))
  end
end

#use(*names) ⇒ Object Also known as: use_scope, includes

Include reusable params rules among current. You can define reusable params with helpers method.

Examples:


class API < Grape::API
  helpers do
    params :pagination do
      optional :page, type: Integer
      optional :per_page, type: Integer
    end
  end

  desc "Get collection"
  params do
    use :pagination
  end
  get do
    Collection.page(params[:page]).per(params[:per_page])
  end
end


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/grape/dsl/parameters.rb', line 58

def use(*names)
  named_params = @api.namespace_stackable_with_hash(:named_params) || {}
  options = names.extract_options!
  names.each do |name|
    params_block = named_params.fetch(name) do
      raise "Params :#{name} not found!"
    end

    if options.empty?
      instance_exec(options, &params_block)
    else
      instance_exec(**options, &params_block)
    end
  end
end

#with(*attrs, &block) ⇒ Object

Define common settings for one or more parameters

Parameters:

  • attrs

    list of parameters names, or, if :using is passed as an option, which keys to include (:all or :none) from the :using hash. The last key can be a hash, which specifies options for the parameters

Options Hash (*attrs):

  • :type (Class)

    the type to coerce this parameter to before passing it to the endpoint. See Validations::Types for a list of types that are supported automatically. Custom classes may be used where they define a class-level ‘::parse` method, or in conjunction with the `:coerce_with` parameter. `JSON` may be supplied to denote `JSON`-formatted objects or arrays of objects. `Array` accepts the same values as `JSON` but will wrap single objects in an `Array`.

  • :types (Array<Class>)

    may be supplied in place of :type to declare an attribute that has multiple allowed types. See Validations::Types::MultipleTypeCoercer for more details on coercion and validation rules for variant-type parameters.

  • :desc (String)

    description to document this parameter

  • :default (Object)

    default value, if parameter is optional

  • :values (Array)

    permissable values for this field. If any other value is given, it will be handled as a validation error

  • :using (Hash[Symbol => Hash])

    a hash defining keys and options, like that returned by Entity#documentation. The value of each key is an options hash accepting the same parameters

  • :except (Array[Symbol])

    a list of keys to exclude from the :using Hash. The meaning of this depends on if :all or :none was passed; :all + :except will make the :except fields optional, whereas :none + :except will make the :except fields required

  • :coerce_with (#parse, #call)

    method to be used when coercing the parameter to the type named by ‘attrs`. Any class or object that defines `::parse` or `::call` may be used.



172
173
174
175
# File 'lib/grape/dsl/parameters.rb', line 172

def with(*attrs, &block)
  new_group_attrs = [@group, attrs.clone.first].compact.reduce(&:deep_merge)
  new_group_scope([new_group_attrs], &block)
end