Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix key validator false negatives on empty collections #363

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since it's skipping empy items now, aren't we going to end up with nils in the resulting array?

Copy link
Contributor Author

@Drenmi Drenmi Jun 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The next keyword optionally accepts one argument which will be taken by the iterator. In this case that would be key.to_s if there are no nested collections. 🙂

3.times.map { |n| next n }
#=> [0, 1, 2]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah doooh of course! Thanks for the explanation 😄

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