Skip to content

Commit

Permalink
Fix validation of keys for hash with no schema
Browse files Browse the repository at this point in the history
  • Loading branch information
JanecekJ committed Oct 18, 2023
1 parent 93eb146 commit af70279
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
2 changes: 2 additions & 0 deletions lib/dry/schema/dsl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,8 @@ def key_spec(name, type)
key_spec(name, type.right)
elsif type.respond_to?(:type)
key_spec(name, type.type)
elsif type.class == Dry::Types::Hash
{name => '*'}
else
name
end
Expand Down
2 changes: 1 addition & 1 deletion lib/dry/schema/key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def read(source)

def write(source, target)
read(source) { |value|
target[coerced_name] = value.is_a?(::Hash) ? members.write(value) : value
target[coerced_name] = value.is_a?(::Hash) && members.keys.map(&:name) != ['*'] ? members.write(value) : value
}
end

Expand Down
6 changes: 5 additions & 1 deletion lib/dry/schema/key_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,11 @@ def validate_path(key_paths, path)

# @api private
def paths_match?(input_path, key_path)
residue = key_path.sub(input_path, "")
residue = if input_path.include?(".") && key_path.end_with?(".*")
"" if input_path.sub(key_path.sub(".*", ""), "").start_with?('.')
else
key_path.sub(input_path, "")
end
residue.empty? || residue.start_with?(DOT, BRACKETS)
end

Expand Down
19 changes: 19 additions & 0 deletions spec/integration/schema/macros/hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,25 @@
end
end

context "with no schema for hash" do
let(:input) do
{foo: {a: 'valid', b: 'also valid'}, bar: "just string"}
end

subject(:schema) do
Dry::Schema.define do
config.validate_keys = true

required(:foo).value(:hash)
required(:bar).value(:string)
end
end

it "is successful" do
expect(result).to be_successful
end
end

context "with hash schema" do
let(:hash_schema) do
Types::Hash.schema(name: "string")
Expand Down

0 comments on commit af70279

Please sign in to comment.