From 2b10b6b0ee5db83b3b9fad65c92707898778f3a7 Mon Sep 17 00:00:00 2001 From: Michael Ball Date: Wed, 14 Aug 2024 03:10:07 -0700 Subject: [PATCH] small validator refactoring --- _plugins/config_validator.rb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/_plugins/config_validator.rb b/_plugins/config_validator.rb index 73b3723..d49aa59 100644 --- a/_plugins/config_validator.rb +++ b/_plugins/config_validator.rb @@ -5,14 +5,17 @@ # 1) Ensures required attributes are present in the config file. # 2) Ensures the baseurl is a consistent format based on the semester # 3) Uses a `course_department` config to implement some shared styling/language. -# Future config validations might make sense, like footer/a11y/etc. +# 4) Ensures the `color_scheme` is valid. +# Future config validations might make sense, like footer/a11y/etc. configuration, # Implement additional validations by registering an entry in `KEY_VALIDATIONS` # This is a key_name => function_name map. # function_name should be defined in the ConfigValidator class, and is called with -# the *value* of the config. +# the key, value pair in the config. # Note that Jekyll parses the YAML file such that the config keys are *strings* not symbols. +# See the inclusion_validator to add simple allow-list style validations + # A simple class for nicer error message formatting. class ConfigValidationError < StandardError attr_reader :errors @@ -55,11 +58,7 @@ def validate validate_keys! KEY_VALIDATIONS.each do |key, validator| - if validator == :inclusion_validator - send(validator, key, config[key.to_s], ConfigValidator.const_get("VALID_#{key.upcase}")) - elsif @config.key?(key.to_s) - send(validator, config[key.to_s]) - end + send(validator, key, config[key.to_s]) if @config.key?(key.to_s) end raise ConfigValidationError, errors if errors.length.positive? @@ -76,12 +75,12 @@ def validate_keys! private - def validate_clean_url(url) + def validate_clean_url(_key, url) errors << '`url` should not end with a `/`' if url.end_with?('/') errors << '`url` should contain a protocol' unless url.match?(%r{https?://}) end - def validate_semester_format(baseurl) + def validate_semester_format(_key, baseurl) # This is just for consistency of URL presentation. errors << '`baseurl` must start with a `/`.' unless baseurl.match?(%r{^/}) # skip, just for the template. @@ -92,7 +91,8 @@ def validate_semester_format(baseurl) errors << "`baseurl` must be a valid semester (faXX, spXX, suXX or wiXX), not #{baseurl}" end - def inclusion_validator(key, value, allowed) + def inclusion_validator(key, value) + allowed = self.class.const_get("VALID_#{key.upcase}") errors << "`#{key}` must be one of #{allowed} (not '#{value}')" unless allowed.include?(value) end end