18F / the-glossary

Glossary for terms encountered at TTS. Machine- and human-readable. Standing on the shoulders of https://github.com/18F/procurement-glossary
4 stars 1 forks source link

Refactor validations into Rules #33

Open beechnut opened 1 year ago

beechnut commented 1 year ago

Having a collection of validation functions and a collection of associated error messages has been fine, and the defensive style of the codebase has made it even more fine.

But when you think of a validation with an error message, it's messy, and it's becoming clear that a new noun is needed—a Rule.

This issue can be closed when:

Ideas:

# lib/validate.rb

require 'lib/rule/term/specific_term_validation'
require 'lib/rule/term/specific_acronym_validation'
# ... and so forth

...

def validate_term(term_data) # I'd love to also make Term an object here so we can just reference the data
  Rule::Term.each { |rule| rule.validate(term_data) }
end
# lib/rule/term/has_description.rb
class Rule::Term::HasDescription < Rule::BaseTerm
  def rule_logic(key, values)
    desc = values[:description]
    if desc.nil?
      reminders << "add a description for \"#{values[:longform] || key}\""
    elsif desc.is_a?(String) && !desc.empty?
      true
    else
      false
    end
  end

  def error_class_name
    :TermMissingDescriptionError # just name the class here, we'll name it in the background
  end

  def message(params) # Define the error message here
    <<~ERR

      The term \"#{key}\" does not have a description.

      ... lines omitted
    ERR
  end

end

Rule::Term.register(Rule::Term::HasDescription) # Makes it accessible to Rule::Term.each
beechnut commented 1 year ago

It might be simpler to use a validation library like dry/validation.