diff --git a/CHANGELOG.md b/CHANGELOG.md index f61ea0727e..29e641bb09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ #### Fixes +* [#1740](https://github.com/ruby-grape/grape/pull/1740): Fix dependent parameter validation using `given` when parameter is a `Hash` - [@jvortmann](https://github.com/jvortmann). + * Your contribution here. ### 1.0.2 (1/10/2018) diff --git a/lib/grape/dsl/parameters.rb b/lib/grape/dsl/parameters.rb index f717028453..bb3196b065 100644 --- a/lib/grape/dsl/parameters.rb +++ b/lib/grape/dsl/parameters.rb @@ -201,7 +201,7 @@ def all_or_none_of(*attrs) # @yield a parameter definition DSL def given(*attrs, &block) attrs.each do |attr| - proxy_attr = attr.is_a?(Hash) ? attr.keys[0] : attr + proxy_attr = first_hash_key_or_param(attr) raise Grape::Exceptions::UnknownParameter.new(proxy_attr) unless declared_param?(proxy_attr) end new_lateral_scope(dependent_on: attrs, &block) @@ -213,7 +213,9 @@ def given(*attrs, &block) def declared_param?(param) # @declared_params also includes hashes of options and such, but those # won't be flattened out. - @declared_params.flatten.include?(param) + @declared_params.flatten.any? do |declared_param| + first_hash_key_or_param(declared_param) == param + end end alias group requires @@ -238,6 +240,12 @@ def params(params) params = map_params(params, @element) if @element params end + + private + + def first_hash_key_or_param(parameter) + parameter.is_a?(Hash) ? parameter.keys.first : parameter + end end end end diff --git a/spec/grape/validations/params_scope_spec.rb b/spec/grape/validations/params_scope_spec.rb index 075db21951..111fadf2e8 100644 --- a/spec/grape/validations/params_scope_spec.rb +++ b/spec/grape/validations/params_scope_spec.rb @@ -466,6 +466,19 @@ def initialize(value) end.to raise_error(Grape::Exceptions::UnknownParameter) end + it 'does not raise an error if the dependent parameter is a Hash' do + expect do + subject.params do + optional :a, type: Hash do + requires :b + end + given :a do + requires :c + end + end + end.to_not raise_error + end + it 'does not validate nested requires when given is false' do subject.params do requires :a, type: String, allow_blank: false, values: %w[x y z]