Skip to content

Commit

Permalink
Merge pull request #672 from alexxty7/670-fix-values-key
Browse files Browse the repository at this point in the history
Fix Undefined method `key?' for nil:NilClass error.
  • Loading branch information
solnic authored Sep 23, 2020
2 parents aca2840 + ae6f78a commit 0f04a17
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/dry/validation/values.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ def key?(key, hash = data)
return result
elsif e.is_a?(Symbol) && a.is_a?(Array)
return false
elsif a.nil?
return false
elsif a.is_a?(String)
return false
else
return false unless a.is_a?(Array) ? (e >= 0 && e < a.size) : a.key?(e)
end
Expand Down
16 changes: 15 additions & 1 deletion spec/unit/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@
end

let(:data) do
{name: "Jane", address: {city: "Paris", geo: {lat: 1, lon: 2}}, phones: [123, 431]}
{
name: "Jane",
address: {city: "Paris", geo: {lat: 1, lon: 2}},
phones: [123, 431],
billing_address: nil,
card: ""
}
end

describe "#[]" do
Expand Down Expand Up @@ -84,6 +90,14 @@
it "returns false when a path to an array is a symbol as its last segment" do
expect(values.key?([:phones, :foo])).to be(false)
end

it "returns false when a nested key is not present and root key is nil" do
expect(values.key?([:billing_address, :not_here])).to be(false)
end

it "returns false when a nested key is not present and root key is string" do
expect(values.key?([:card, :not_here])).to be(false)
end
end

describe "#dig" do
Expand Down

0 comments on commit 0f04a17

Please sign in to comment.