mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
[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
This commit is contained in:
parent
3c6bb89271
commit
877e42e232
2 changed files with 25 additions and 0 deletions
|
@ -252,7 +252,15 @@ module ActionController
|
||||||
#
|
#
|
||||||
# ActionController::Parameters.new(person: {}).require(:person)
|
# ActionController::Parameters.new(person: {}).require(:person)
|
||||||
# # => ActionController::ParameterMissing: param is missing or the value is empty: 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)
|
def require(key)
|
||||||
|
return keys.map { |k| require(k) } if key.is_a?(Array)
|
||||||
value = self[key]
|
value = self[key]
|
||||||
if value.present? || value == false
|
if value.present? || value == false
|
||||||
value
|
value
|
||||||
|
|
|
@ -48,4 +48,21 @@ class ParametersRequireTest < ActiveSupport::TestCase
|
||||||
ActionController::Parameters.new(person: {}).require(:person)
|
ActionController::Parameters.new(person: {}).require(:person)
|
||||||
end
|
end
|
||||||
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
|
end
|
||||||
|
|
Loading…
Reference in a new issue