Module: ShortUUID
- Defined in:
- lib/shortuuid.rb,
lib/shortuuid/version.rb
Constant Summary collapse
- DEFAULT_BASE62 =
%w[0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z].freeze
- VERSION =
'0.6.0'.freeze
Class Method Summary collapse
- .convert_alphabet_to_decimal(word, alphabet = DEFAULT_BASE62) ⇒ Object
- .convert_decimal_to_alphabet(decimal, alphabet = DEFAULT_BASE62) ⇒ Object
- .decode(word, alphabet = DEFAULT_BASE62) ⇒ Object
- .encode(number, alphabet = DEFAULT_BASE62) ⇒ Object
- .expand(short_uuid, alphabet = DEFAULT_BASE62) ⇒ Object
- .shorten(uuid, alphabet = DEFAULT_BASE62) ⇒ Object
Class Method Details
.convert_alphabet_to_decimal(word, alphabet = DEFAULT_BASE62) ⇒ Object
28 29 30 31 32 33 34 35 |
# File 'lib/shortuuid.rb', line 28 def self.convert_alphabet_to_decimal(word, alphabet = DEFAULT_BASE62) num = 0 radix = alphabet.length word.chars.to_a.reverse.each_with_index do |char, index| num += alphabet.index(char) * (radix**index) end num end |
.convert_decimal_to_alphabet(decimal, alphabet = DEFAULT_BASE62) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/shortuuid.rb', line 14 def self.convert_decimal_to_alphabet(decimal, alphabet = DEFAULT_BASE62) alphabet = alphabet.to_a radix = alphabet.length i = decimal.to_i out = [] return alphabet[0] if i.zero? loop do break if i.zero? out.unshift(alphabet[i % radix]) i /= radix end out.join end |
.decode(word, alphabet = DEFAULT_BASE62) ⇒ Object
41 42 43 |
# File 'lib/shortuuid.rb', line 41 def self.decode(word, alphabet = DEFAULT_BASE62) convert_alphabet_to_decimal(word, alphabet) end |
.encode(number, alphabet = DEFAULT_BASE62) ⇒ Object
37 38 39 |
# File 'lib/shortuuid.rb', line 37 def self.encode(number, alphabet = DEFAULT_BASE62) convert_decimal_to_alphabet(number, alphabet) end |
.expand(short_uuid, alphabet = DEFAULT_BASE62) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/shortuuid.rb', line 45 def self.(short_uuid, alphabet = DEFAULT_BASE62) return nil unless short_uuid && !short_uuid.empty? decimal_value = convert_alphabet_to_decimal(short_uuid, alphabet) uuid = decimal_value.to_s(16).rjust(32, '0') [ uuid[0..7], uuid[8..11], uuid[12..15], uuid[16..19], uuid[20..31] ].join('-') end |
.shorten(uuid, alphabet = DEFAULT_BASE62) ⇒ Object
8 9 10 11 12 |
# File 'lib/shortuuid.rb', line 8 def self.shorten(uuid, alphabet = DEFAULT_BASE62) return nil unless uuid && !uuid.empty? decimal_value = uuid.split('-').join.to_i(16) convert_decimal_to_alphabet(decimal_value, alphabet) end |