Sha256: 1bdfd12efeb5a9f12428863472e2a567ae9843b0383cad1872f35d702e8351fa

Contents?: true

Size: 1.01 KB

Versions: 3

Compression:

Stored size: 1.01 KB

Contents

module NxtErrorRegistry
  class DefaultCodeValidator
    CodeAlreadyTakenError = Class.new(StandardError)
    InvalidCodeFormatError = Class.new(StandardError)

    LEGACY_FORMAT = /\A\d{3}\.\d{3}\z/
    FORMAT = /\A[a-zA-Z0-9-]{36}|#{LEGACY_FORMAT}\z/

    def initialize(name, type, code, context)
      @name = name
      @type = type
      @code = code
      @context = context
    end

    def validate
      validate_code_format
      validate_code_uniqueness

      code
    end

    private

    attr_reader :name, :type, :code, :context

    def validate_code_format
      return if code =~ FORMAT

      raise InvalidCodeFormatError, "Code #{code} for name #{name} violates format #{FORMAT} in context: #{context}"
    end

    def validate_code_uniqueness
      duplicates = registry.duplicated_codes
      return if duplicates.empty?

      raise CodeAlreadyTakenError, "The following codes are duplicated: #{duplicates.keys.join(',')}"
    end

    def registry
      NxtErrorRegistry::Registry.instance
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nxt_error_registry-0.3.0 lib/nxt_error_registry/default_code_validator.rb
nxt_error_registry-0.2.5 lib/nxt_error_registry/default_code_validator.rb
nxt_error_registry-0.2.4 lib/nxt_error_registry/default_code_validator.rb