module NxtErrorRegistry

Constants

CodeValidator
RegistrationError
VERSION

Public Instance Methods

register_error(name, type:, code:, **opts, &block) click to toggle source
# File lib/nxt_error_registry.rb, line 12
def register_error(name, type:, code:, **opts, &block)
  raise_name_not_a_symbol_error(name) unless name.is_a?(Symbol)
  raise_registration_error(name) if const_defined?(name)

  error_class = Class.new(type, &block)
  error_class.define_singleton_method :code, -> { code }
  error_class.define_singleton_method :options do
    # the superclass "type" may not have defined options yet
    inherited_options = type.try(:options) || {}
    inherited_options.merge(opts)
  end

  const_set(name, error_class)
  # Calling `delegate` before `const_set` would rip off the modules from the error class.
  # e.g. `Module1::Module2::MyError` would become `MyError`.
  error_class.delegate :code, to: :class

  entry = { code: code, error_class: error_class, type: type, name: name, namespace: self.to_s, opts: opts }
  error_registry[name.to_s] = entry

  # This depends on duplicate entries so has to come last
  validate_code(name, type, code)
end

Private Instance Methods

error_registry() click to toggle source
# File lib/nxt_error_registry.rb, line 42
def error_registry
  @error_registry ||= begin
    ::NxtErrorRegistry::Registry.instance[self.to_s] ||= { }
    ::NxtErrorRegistry::Registry.instance[self.to_s]
  end
end
raise_name_not_a_symbol_error(name) click to toggle source
# File lib/nxt_error_registry.rb, line 53
def raise_name_not_a_symbol_error(name)
  raise ArgumentError, "Error name '#{name}' must be a symbol"
end
raise_registration_error(name) click to toggle source
# File lib/nxt_error_registry.rb, line 49
def raise_registration_error(name)
  raise RegistrationError, "#{name} was already registered in #{self}"
end
validate_code(name, type, code) click to toggle source
# File lib/nxt_error_registry.rb, line 38
def validate_code(name, type, code)
  CodeValidator.new(name, type, code, self).validate
end