Skip to content

Commit 1dd02dd

Browse files
authored
Merge pull request #1740 from jvortmann/master
Fix exception being thrown when dependent parameter is a Hash
2 parents 16c6662 + f52d473 commit 1dd02dd

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
#### Fixes
88

9+
* [#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).
10+
911
* Your contribution here.
1012

1113
### 1.0.2 (1/10/2018)

lib/grape/dsl/parameters.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ def all_or_none_of(*attrs)
201201
# @yield a parameter definition DSL
202202
def given(*attrs, &block)
203203
attrs.each do |attr|
204-
proxy_attr = attr.is_a?(Hash) ? attr.keys[0] : attr
204+
proxy_attr = first_hash_key_or_param(attr)
205205
raise Grape::Exceptions::UnknownParameter.new(proxy_attr) unless declared_param?(proxy_attr)
206206
end
207207
new_lateral_scope(dependent_on: attrs, &block)
@@ -213,7 +213,9 @@ def given(*attrs, &block)
213213
def declared_param?(param)
214214
# @declared_params also includes hashes of options and such, but those
215215
# won't be flattened out.
216-
@declared_params.flatten.include?(param)
216+
@declared_params.flatten.any? do |declared_param|
217+
first_hash_key_or_param(declared_param) == param
218+
end
217219
end
218220

219221
alias group requires
@@ -238,6 +240,12 @@ def params(params)
238240
params = map_params(params, @element) if @element
239241
params
240242
end
243+
244+
private
245+
246+
def first_hash_key_or_param(parameter)
247+
parameter.is_a?(Hash) ? parameter.keys.first : parameter
248+
end
241249
end
242250
end
243251
end

spec/grape/validations/params_scope_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,19 @@ def initialize(value)
466466
end.to raise_error(Grape::Exceptions::UnknownParameter)
467467
end
468468

469+
it 'does not raise an error if the dependent parameter is a Hash' do
470+
expect do
471+
subject.params do
472+
optional :a, type: Hash do
473+
requires :b
474+
end
475+
given :a do
476+
requires :c
477+
end
478+
end
479+
end.to_not raise_error
480+
end
481+
469482
it 'does not validate nested requires when given is false' do
470483
subject.params do
471484
requires :a, type: String, allow_blank: false, values: %w[x y z]

0 commit comments

Comments
 (0)