Module: Cuid

Defined in:
lib/cuid.rb

Overview

Cuid is a library for generating unique collision-resistant IDs optimized for horizontal scaling and performance

Examples:

Generate a hash

hash = Cuid::generate #=> "ch8qypsnz0000a4welw8anyr"

Generate 2 hashes

hashes = Cuid::generate(2) #=> ["ch8qyq35f0002a4wekjcwmh30", "ch8qyq35f0003a4weewy22izq"]

See Also:

Constant Summary collapse

BLOCK_SIZE =

length of each segment of the hash

4
BASE =

size of the alphabet (e.g. base36 is [a-z0-9])

36
RAND_SIZE =

size of the random segment of the block

BLOCK_SIZE * 2

Class Method Summary collapse

Class Method Details

.generateString .generate(quantity) ⇒ Array<String> .generate(quantity, secure_random) ⇒ Array<String>

Returns one or more hashes based on the parameter supplied

Overloads:

  • .generateString

    Returns one hash when called with no parameters or a parameter of 1

    Parameters:

    • quantity (optional, Integer)

      determines number of hashes returned (must be nil, 0 or 1)

    Returns:

    • (String)
  • .generate(quantity) ⇒ Array<String>

    Returns an array of hashes when called with a parameter greater than 1

    Parameters:

    • quantity (Integer)

      determines number of hashes returned (must be greater than 1)

    Returns:

    • (Array<String>)
  • .generate(quantity, secure_random) ⇒ Array<String>

    Returns an array of hashes when called with a parameter greater than 1

    Parameters:

    • quantity (Integer)

      determines number of hashes returned (must be greater than 1)

    • secure_random (Boolean)

      attempts to use SecureRandom if set to True (Ruby 1.9.2 and up; reverts to Kernel#rand if SecureRandom is not supported)

    Returns:

    • (Array<String>)


79
80
81
82
83
84
85
86
# File 'lib/cuid.rb', line 79

def generate(quantity=1,secure_random=false)
  @use_secure_random = secure_random
  @fingerprint = get_fingerprint # only need to get the fingerprint once because it is constant per-run
  return api unless quantity > 1

  values = Array(1.upto(quantity)) # create an array of the correct size
  return values.collect { api } # fill array with hashes
end

.validate(str) ⇒ Boolean

Validates (minimally) the supplied string is in the correct format to be a hash

Validation checks that the first letter is correct and that the rest of the string is the correct length and consists of lower case letters and numbers.

Parameters:

  • str (String)

    string to check

Returns:

  • (Boolean)

    returns true if the format is correct



96
97
98
99
# File 'lib/cuid.rb', line 96

def validate(str)
  blen = BLOCK_SIZE * 6
  !!str.match(/#{LETTER}[a-z0-9]{#{blen}}/)
end