Skip to content

Commit

Permalink
Merge pull request #363 from Drenmi/bugfix/key-validator-on-empty-col…
Browse files Browse the repository at this point in the history
…lections

[changelog]

fixed: "Fix key validator false negatives on empty collections (see #363) (@Drenmi)"
  • Loading branch information
solnic authored Jun 18, 2021
2 parents 4e09e5e + 7c129f7 commit 21ebe40
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
7 changes: 6 additions & 1 deletion lib/dry/schema/key_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,14 @@ def key_paths(hash)
hash.flat_map { |key, _|
case (value = hash[key])
when Hash
next key.to_s if value.empty?

[key].product(key_paths(hash[key])).map { |keys| keys.join(DOT) }
when Array
hashes_or_arrays = value.select { |e| e.is_a?(Array) || e.is_a?(Hash) }
hashes_or_arrays = value.select { |e| (e.is_a?(Array) || e.is_a?(Hash)) && !e.empty? }

next key.to_s if hashes_or_arrays.empty?

hashes_or_arrays.flat_map.with_index { |el, idx|
key_paths(el).map { |path| ["#{key}[#{idx}]", *path].join(DOT) }
}
Expand Down
10 changes: 8 additions & 2 deletions spec/integration/schema/unexpected_keys_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
foo: "unexpected",
name: "Jane",
ids: [1, 2, 3, 4],
address: {bar: "unexpected", city: "NYC", zipcode: "1234"},
qux: [],
quux: [{}],
hoge: {},
address: {bar: "unexpected", baz: [1], city: "NYC", zipcode: "1234"},
roles: [
{name: "admin", expires_at: Date.today},
{name: "editor", foo: "unexpected", expires_at: Date.today}
Expand All @@ -35,7 +38,10 @@
expect(schema.(input).errors.to_h)
.to eql(
foo: ["is not allowed"],
address: {bar: ["is not allowed"]},
qux: ["is not allowed"],
quux: ["is not allowed"],
hoge: ["is not allowed"],
address: {bar: ["is not allowed"], baz: ["is not allowed"]},
roles: {1 => {foo: ["is not allowed"]}}
)
end
Expand Down

0 comments on commit 21ebe40

Please sign in to comment.