Improve requiring of scalar parameters #44297
Open
+122
−36
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
The usage of
ActionController::Parameters#require
is a bit ambiguous.It can be called for hashes, arrays and scalar values.
When a scalar value is expected but a hash is passed you might get
unexpected results:
Similarly, when a hash is expected but a scalar value is passed:
This requires developers to handle these unexpected exceptions instead
of just rescuing/ignoring
ActionController::ParameterMissing
.There even is a warning documented in the rdoc of
require
to becareful when requiring terminal values. For example, calling require
without permit can have unexpected results if unpermitted values are
passed:
Separate
require
methods for scalar and non scalar paramsBy restricting
require
to arrays and hashes, and adding arequire_scalar
method for scalar values we can prevent these problems.This allows us to raise an
ActionController::ParameterMissing
if arequired param doesn't have the expected type:
require_scalar
also restricts the required values to permittedscalar values.
Fixes: #42953
Other Information
This would be a breaking change requiring deprecation warnings.
Maybe we should make it even stricter and introduce methods
for each permited scalar type. This allows us to have stricter
checks and maybe even coerce to the proper type: