From 877e42e2321d544a50edaf23291130f131d6879d Mon Sep 17 00:00:00 2001 From: Gaurish Sharma Date: Sat, 28 Mar 2015 12:08:36 +0530 Subject: [PATCH] [Feature] params.require requires array of params This PR adds ability to accept arrays which allows you to require multiple values in one method. so instead of this: ```ruby params.require(:person).require(:first_name) params.require(:person).require(:last_name) ``` Here it will be one line for each params, so say if I require 10params, it will be 10lines of repeated code which is not dry. So I have added new method which does this in one line: ```ruby params.require(:person).require([:first_name, :last_name]) ``` Comments welcome --- .../metal/strong_parameters.rb | 8 ++++++++ .../test/controller/required_params_test.rb | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index fc8e345d43..02599a4654 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -252,7 +252,15 @@ module ActionController # # ActionController::Parameters.new(person: {}).require(:person) # # => ActionController::ParameterMissing: param is missing or the value is empty: person + # + # ActionController::Parameters.new(first_name: 'Gaurish', title: nil).require([:first_name, :title]) + # # => ActionController::ParameterMissing: param is missing or the value is empty: title + # + # params = ActionController::Parameters.new(first_name: 'Gaurish', title: Mjallo) + # first_name, title = params.require([:first_name, :title]) + # def require(key) + return keys.map { |k| require(k) } if key.is_a?(Array) value = self[key] if value.present? || value == false value diff --git a/actionpack/test/controller/required_params_test.rb b/actionpack/test/controller/required_params_test.rb index a901e56332..98b8e44b22 100644 --- a/actionpack/test/controller/required_params_test.rb +++ b/actionpack/test/controller/required_params_test.rb @@ -48,4 +48,21 @@ class ParametersRequireTest < ActiveSupport::TestCase ActionController::Parameters.new(person: {}).require(:person) end end + + test "require array of params" do + safe_params = ActionController::Parameters.new(person: {first_name: 'Gaurish', title: 'Mjallo'}) + .require(:person) + .require([:first_name, :last_name]) + + assert_kind_of Array, safe_params + assert_equal ['Gaurish', 'Mjallo'], safe_params + end + + test "require array when it contains a nil values" do + assert_raises(ActionController::ParameterMissing) do + safe_params = ActionController::Parameters.new(person: {first_name: 'Gaurish', title: nil}) + .require(:person) + .require([:first_name, :last_name]) + end + end end