Class: Rack::Params::HashContext

Inherits:
Context
  • Object
show all
Defined in:
lib/rack/params/context.rb

Overview

the DSL for validating a hash parameter (including the top-level params hash)

Constant Summary

Result =
Hash

Instance Method Summary collapse

Constructor Details

This class inherits a constructor from Rack::Params::Context

Instance Method Details

#param(key, type, options = {}) { ... } ⇒ Object

do type coercion and validation for a parameter with the given key. adds the coerced value to the result hash, or push an error.

Parameters:

  • key

    the key in the hash of the parameter to validate

  • type

    the type to coerce the value into

  • options (Hash) (defaults to: {})

Yields:

  • if type is Hash or Array, passing a block will recursively validate the coerced value, assuming the block is a new validation context.

Returns:

  • the coerced value

See Also:



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/rack/params/context.rb', line 137

def param(key, type, options = {}, &block)
  key = key.to_s

  # default and required
  value = params[key] || options[:default]
  raise ArgumentError, "is required" if options[:required] && value.nil?

  # type cast
  value = _coerce(value, type, options)

  # validate against rules
  # options.each { |v, vopts| _validate(key, value, v, vopts) }

  # recurse if we've got a block
  if block_given?
    value = _recurse(key, type, value, &block)
    result.errors.merge! value.errors
  end

  # return - we're good
  result[key] = value
rescue ArgumentError => ex
  path = [@path, key].reject(&:nil?).join(".")
  result.errors[path] << ex.message
  nil
end

#splat(key, options = {}) ⇒ Object

collect uncoerced keys from the parameter hash into the results hash. collects keys not yet coerced, so it should be last in the validation block.

Parameters:

  • key

    the result key under which to place the collected parameters

  • options (Hash) (defaults to: {})

Returns:

  • the collected keys as a hash



170
171
172
173
174
175
176
# File 'lib/rack/params/context.rb', line 170

def splat(key, options = {})
  key = key.to_s

  # every key in params that's not already in results
  value = params.reject { |k, _| result.keys.include? k }
  result[key] = value
end