From 54a1fea74ed3fddcc791a397df9284ee2b314676 Mon Sep 17 00:00:00 2001 From: Alan Guo Xiang Tan Date: Wed, 28 Feb 2024 10:44:46 +0800 Subject: [PATCH] DEV: Refactor `ThemeSettingsObjectValidator#validate` (#25904) What does this change do? 1. Reduce an additional loop through all the properties 2. Extract the validation of child objects into a dedicate method --- lib/theme_settings_object_validator.rb | 47 +++++++++++++++----------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/lib/theme_settings_object_validator.rb b/lib/theme_settings_object_validator.rb index 7463ad3d847..3939ca18632 100644 --- a/lib/theme_settings_object_validator.rb +++ b/lib/theme_settings_object_validator.rb @@ -70,22 +70,15 @@ class ThemeSettingsObjectValidator end def validate - validate_properties - @properties.each do |property_name, property_attributes| if property_attributes[:type] == "objects" - @object[property_name]&.each_with_index do |child_object, index| - self - .class - .new( - schema: property_attributes[:schema], - object: child_object, - json_pointer_prefix: "#{@json_pointer_prefix}#{property_name}/#{index}/", - valid_ids_lookup:, - errors: @errors, - ) - .validate - end + validate_child_objects( + @object[property_name], + property_name:, + schema: property_attributes[:schema], + ) + else + validate_property(property_name, property_attributes) end end @@ -94,15 +87,29 @@ class ThemeSettingsObjectValidator private - def validate_properties - @properties.each do |property_name, property_attributes| - next if property_attributes[:type] == "objects" - next if property_attributes[:required] && !is_property_present?(property_name) - next if !has_valid_property_value_type?(property_attributes, property_name) - next if !has_valid_property_value?(property_attributes, property_name) + def validate_child_objects(objects, property_name:, schema:) + return if objects.blank? + + objects.each_with_index do |object, index| + self + .class + .new( + schema:, + object:, + valid_ids_lookup:, + json_pointer_prefix: "#{@json_pointer_prefix}#{property_name}/#{index}/", + errors: @errors, + ) + .validate end end + def validate_property(property_name, property_attributes) + return if property_attributes[:required] && !is_property_present?(property_name) + return if !has_valid_property_value_type?(property_attributes, property_name) + !has_valid_property_value?(property_attributes, property_name) + end + def has_valid_property_value_type?(property_attributes, property_name) value = @object[property_name] type = property_attributes[:type]