Skip to content

Commit

Permalink
fixed undeclared for nested params
Browse files Browse the repository at this point in the history
  • Loading branch information
hobofan committed Sep 23, 2015
1 parent b2c1ba4 commit f008ad3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
29 changes: 26 additions & 3 deletions lib/grape/dsl/parameters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,32 @@ def given(attr, &block)
# block yet.
# @returns [Boolean] whether the parameter has been defined
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)
# converts params into a nested hash with true as deepest values
convert_hash = lambda do |obj|
return [obj, true] unless obj.is_a?(Array) || obj.is_a?(Hash)
if obj.is_a? Array
return obj.map { |e| convert_hash.call(e) }
elsif obj.is_a? Hash
obj.map do |k, v|
return k, convert_hash.call(v).to_h
end
end
end

# very simple hash inclusion check
included = lambda do |bigger, smaller|
return true if bigger == smaller
return false unless smaller.is_a?(Hash) # no match found and we can't go deeper

key = smaller.keys.first

return included.call(bigger[key], smaller[key])
end

conv_declared_params = convert_hash.call(@declared_params).to_h
conv_param = convert_hash.call([param]).to_h

included.call(conv_declared_params, conv_param)
end

# Test if this parameter has been declared as a block
Expand Down
4 changes: 4 additions & 0 deletions spec/grape/validations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1345,9 +1345,13 @@ module SharedParams
subject.params undeclared: :error do
optional :hash, type: Hash do
optional :key
optional :unrelated_key
end
optional :array, type: Array do
optional :key
optional :unrelated_key, type: Hash do
optional :deep_nested
end
end
end
subject.get('/undeclared') { 'undeclared works' }
Expand Down

0 comments on commit f008ad3

Please sign in to comment.