Skip to content

Commit

Permalink
Merge pull request #709 from bautrey37/fix-rule.each-on-optional-value
Browse files Browse the repository at this point in the history
Fix rule.each on optional value

Closes #708
  • Loading branch information
solnic committed May 28, 2022
2 parents 3051387 + 035f880 commit 10a9d68
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/dry/validation/rule.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def each(*macros, &block)
@keys = []

@block = proc do
unless result.base_error?(root) || !values.key?(root)
unless result.base_error?(root) || !values.key?(root) || values[root].nil?
values[root].each_with_index do |_, idx|
path = [*Schema::Path[root].to_a, idx]

Expand Down
3 changes: 0 additions & 3 deletions lib/dry/validation/values.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ def [](*args)
def key?(key, hash = data)
return hash.key?(key) if key.is_a?(Symbol)

# rubocop: disable Lint/DuplicateBranch
Schema::Path[key].reduce(hash) do |a, e|
if e.is_a?(Array)
result = e.all? { |k| key?(k, a) }
Expand All @@ -81,8 +80,6 @@ def key?(key, hash = data)
end
a[e]
end
# rubocop: enable Lint/DuplicateBranch

true
end
# rubocop: enable Metrics/PerceivedComplexity
Expand Down
20 changes: 20 additions & 0 deletions spec/unit/rule_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,24 @@
end
end
end

context "with an optional value" do
let(:contract_class) do
Class.new(Dry::Validation::Contract) do
schema do
required(:tags).maybe(:array)
end
end
end

context "when using .each macro" do
it "does not fail when input is nil" do
contract_class.rule(:tags).each do
key.failure("should not be called")
end

expect(contract.(tags: nil).errors.to_h).to eq({})
end
end
end
end

0 comments on commit 10a9d68

Please sign in to comment.