Skip to content

Commit

Permalink
Merge pull request #1740 from jvortmann/master
Browse files Browse the repository at this point in the history
Fix exception being thrown when dependent parameter is a Hash
  • Loading branch information
dblock committed Feb 6, 2018
2 parents 16c6662 + f52d473 commit 1dd02dd
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 10 additions & 2 deletions lib/grape/dsl/parameters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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
13 changes: 13 additions & 0 deletions spec/grape/validations/params_scope_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit 1dd02dd

Please sign in to comment.