Module: Baseh::Zero

Defined in:
lib/baseh/zero.rb

Overview

Zero-config pair over the frozen baseh-medium-v1 profile. No profile object, no key: just the two functions an application needs when it does not want to think about configuration.

Baseh.to_code(481890303)     -> "ZZZZZZV"
Baseh.from_code("ZZZZZZV")   -> 481890303

to_code accepts an Integer or a decimal string of digits. from_code strips every whitespace character (edges and internal), accepts lowercase and the typed aliases (O, I, L) and returns the id as an Integer. Any invalid input raises BasehError, including the rare BLOCKED_CODE identifiers that spell a blocklisted word; no correction attempts are ever made.

Constant Summary collapse

DECIMAL =
/\A[0-9]+\z/.freeze
WHITESPACE =
/\s+/.freeze
ZERO =
Baseh.new(Profiles.baseh_medium_v1)

Class Method Summary collapse

Class Method Details

.from_code(code) ⇒ Integer

Decode a code from the zero-config Medium profile back to its id.

Parameters:

  • code (String)

Returns:

  • (Integer)

Raises:

  • (BasehError)

    INVALID_LENGTH, INVALID_CHARACTER, INVALID_CHECKSUM



54
55
56
57
# File 'lib/baseh/zero.rb', line 54

def from_code(code)
  input = code.is_a?(String) ? code.gsub(WHITESPACE, "") : code
  ZERO.decode(input).id
end

.to_code(id) ⇒ String

Encode an identifier with the zero-config Medium profile.

Parameters:

  • id (Integer, String)

    Integer or decimal string of digits

Returns:

  • (String)

    canonical code

Raises:

  • (ArgumentError)

    when id is neither an Integer nor a decimal string

  • (BasehError)

    OUT_OF_RANGE, BLOCKED_CODE



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/baseh/zero.rb', line 31

def to_code(id)
  value =
    case id
    when Integer then id
    when String
      if DECIMAL.match?(id)
        id.to_i
      else
        raise ArgumentError,
              "to_code expects a non-negative Integer or a decimal string"
      end
    else
      raise ArgumentError,
            "to_code expects a non-negative Integer or a decimal string"
    end
  ZERO.encode(id: value)
end