Class: EncodedId::Alphabet

Inherits:
Object
  • Object
show all
Defined in:
lib/encoded_id/alphabet.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(characters, equivalences = nil) ⇒ Alphabet

Returns a new instance of Alphabet.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/encoded_id/alphabet.rb', line 5

def initialize(characters, equivalences = nil)
  unless (characters.is_a?(Array) || characters.is_a?(String)) && characters.size > 0
    raise InvalidAlphabetError, "Alphabet must be a string or array"
  end
  unique_alphabet = (characters.is_a?(Array) ? characters : characters.chars).uniq
  raise InvalidAlphabetError, "Alphabet must be at least 16 unique characters" if unique_alphabet.size < 16
  @characters = unique_alphabet.join

  # Equivalences is a hash of characters to their equivalent character.
  # Characters to be mapped must not be in the alphabet, and must map to a character that is in the alphabet.
  raise InvalidConfigurationError, "Character equivalences must be a hash or nil" unless equivalences.nil? || equivalences.is_a?(Hash)
  valid_equivalences = equivalences.nil? || (unique_alphabet & equivalences.keys).empty? && (equivalences.values - unique_alphabet).empty?
  raise InvalidConfigurationError unless valid_equivalences
  @equivalences = equivalences
end

Instance Attribute Details

#charactersObject (readonly)

Returns the value of attribute characters.



21
22
23
# File 'lib/encoded_id/alphabet.rb', line 21

def characters
  @characters
end

#equivalencesObject (readonly)

Returns the value of attribute equivalences.



21
22
23
# File 'lib/encoded_id/alphabet.rb', line 21

def equivalences
  @equivalences
end

Class Method Details

.modified_crockfordObject



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/encoded_id/alphabet.rb', line 24

def modified_crockford
  # Note we downcase first, so mappings are only for lower case. Also Crockford suggests i==1,
  # but here i==j is used.

  new(
    "0123456789abcdefghjkmnpqrstuvwxyz",
    {
      "o" => "0",
      "i" => "j",
      "l" => "1"
    }
  )
end