Skip to content

Instantly share code, notes, and snippets.

@Hasstrup
Last active November 5, 2024 19:16
Show Gist options
  • Select an option

  • Save Hasstrup/a2df7e901918f2c4e9abafea3aa9966c to your computer and use it in GitHub Desktop.

Select an option

Save Hasstrup/a2df7e901918f2c4e9abafea3aa9966c to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# Provides validation methods for input classes.
module Validation
def valid?
validate!
errors.empty?
end
def validate!
raise NotImplementedError
end
private
def pipe_error(error)
@errors << error
end
def error(message)
BaseInput::InputValidationError.new(message)
end
def validate_association!(id, klass, conditional: false)
within_error_context do
return if conditional && id.blank?
pipe_error(relation_not_found_error(klass.to_s, id)) unless klass.exists?(id:)
end
end
def validate_required_keys!
within_error_context do
self.class::REQUIRED_KEYS.each do |key|
validate_presence_of(key)
end
end
end
def within_error_context(&block)
block.call if errors.empty?
end
def collate_errors_for(*keys)
keys.each do |key|
within_error_context do
target = send(key)
next @errors += target.errors if target.respond_to?(:valid?) && !target.valid?
target.each do |node|
within_error_context do
@errors += node.errors unless node.valid?
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment