Skip to content

Commit

Permalink
small validator refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
cycomachead committed Aug 14, 2024
1 parent 687e96e commit 2b10b6b
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions _plugins/config_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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?
Expand All @@ -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.
Expand All @@ -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
Expand Down

0 comments on commit 2b10b6b

Please sign in to comment.