Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve requiring of scalar parameters #44297

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Commits on Jan 31, 2022

  1. Split Parameters#require method for scalar and non-scalar values

    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:
    
        ActionController::Parameters.new(name: { first: "Francesco" }).require(:name).downcase
        NoMethodError (undefined method `downcase' for #<ActionController::Parameters:0x00007f8c631264b0>)
    
    Similarly, when a hash is expected but a scalar value is passed:
    
        ActionController::Parameters.new(name: "Francesco").require(:name).permit
        NoMethodError (undefined method `permit' for "Francesco":String)
    
    There even is a warning documented in the rdoc of `require` to be
    careful when requiring terminal values. For example, calling require
    without permit can have unexpected results if unpermitted values are
    passed:
    
        ActionController::Parameters.new(name: Object.new).require(:name)
        # => #<Object:0x00007f8c58637180>
    
    By restricting `require` to arrays and hashes, and adding a
    `require_scalar` method for scalar values we can prevent these problems.
    `require_scalar` can also restrict the required values to permitted
    scalar values.
    p8 committed Jan 31, 2022
    Copy the full SHA
    6e260aa View commit details
    Browse the repository at this point in the history