From e947f2a6804f01f772312fc9757bc26c5edcc6c1 Mon Sep 17 00:00:00 2001 From: David Harsha Date: Sat, 16 Dec 2023 14:44:55 -0800 Subject: [PATCH] Pass resolved instance location to custom keywords Never meant to expose `Location` hashes. Looks like this was an oversight when they were introduced. Noticed this while looking into: https://github.com/davishmcclurg/json_schemer/issues/166 --- lib/json_schemer/schema.rb | 3 ++- test/json_schemer_test.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/json_schemer/schema.rb b/lib/json_schemer/schema.rb index 39801e0..21d5fcd 100644 --- a/lib/json_schemer/schema.rb +++ b/lib/json_schemer/schema.rb @@ -149,9 +149,10 @@ def validate_instance(instance, instance_location, keyword_location, context) end if root.custom_keywords.any? + resolved_instance_location = Location.resolve(instance_location) root.custom_keywords.each do |custom_keyword, callable| if value.key?(custom_keyword) - [*callable.call(instance, value, instance_location)].each do |custom_keyword_result| + [*callable.call(instance, value, resolved_instance_location)].each do |custom_keyword_result| custom_keyword_valid = custom_keyword_result == true valid &&= custom_keyword_valid type = custom_keyword_result.is_a?(String) ? custom_keyword_result : custom_keyword diff --git a/test/json_schemer_test.rb b/test/json_schemer_test.rb index 5eb1012..f4fe278 100644 --- a/test/json_schemer_test.rb +++ b/test/json_schemer_test.rb @@ -228,6 +228,32 @@ def test_it_validates_custom_keywords_in_nested_schemas refute(schemer.valid?({ 'x' => 'invalid' })) end + def test_custom_keywords_receive_resolved_instance_location + custom_keyword_instance_location = nil + schemer = JSONSchemer.schema( + { + 'properties' => { + 'x' => { + 'yah' => true + }, + 'y' => { + 'yah' => true + } + } + }, + keywords: { + 'yah' => proc do |instance, _schema, instance_location| + custom_keyword_instance_location = instance_location + instance == 'valid' + end + } + ) + assert(schemer.valid?({ 'x' => 'valid' })) + assert_equal('/x', custom_keyword_instance_location) + refute(schemer.valid?({ 'y' => 'invalid' })) + assert_equal('/y', custom_keyword_instance_location) + end + def test_it_handles_multiple_of_floats assert(JSONSchemer.schema({ 'multipleOf' => 0.01 }).valid?(8.61)) refute(JSONSchemer.schema({ 'multipleOf' => 0.01 }).valid?(8.666))