Class: Hoodoo::UUID

Inherits:
Object
  • Object
show all
Defined in:
lib/hoodoo/utilities/uuid.rb

Overview

Class that handles generation and validation of UUIDs. Whenever you want to associate an identifier with something, you should use this class rather than (e.g.) relying on identifiers generated by a database. This allows you to cluster your database later on, should your application become big enough, without having to worry about ID synchronisation across instances.

Constant Summary collapse

MATCH_16_PAIRS_OF_HEX_DIGITS =

A regexp which, as its name suggests, only matches a string that contains 16 pairs of hex digits (with upper or lower case A-F). Legacy value kept in case third party client code is using it.

stackoverflow.com/questions/287684/regular-expression-to-validate-hex-string

/^([[:xdigit:]]{2}){16}$/
MATCH_V4_UUID =

A regexp which matches V4 UUIDs with hyphens removed. Note that this is more strict than MATCH_16_PAIRS_OF_HEX_DIGITS.

/^[a-fA-F0-9]{12}4[a-fA-F0-9]{3}[89aAbB][a-fA-F0-9]{15}$/

Class Method Summary collapse

Class Method Details

.generateObject

Generate a unique identifier. Returns a 32 character string.



29
30
31
# File 'lib/hoodoo/utilities/uuid.rb', line 29

def self.generate
  ::SecureRandom.uuid().gsub!( '-', '' )
end

.valid?(uuid) ⇒ Boolean

Checks if a UUID string is valid. Returns true if so, else false.

uuid

Quantity to validate.

The method will only return true if the input parameter is a String containing 32 mostly random hex digits representing a valid V4 UUID with hyphens removed.

Note that the validity of a UUID says nothing about where, if anywhere, it might have been used. So, just because a UUID is valid, doesn’t mean you have (say) stored something with that UUID as the primary key in a row in a database.

Returns:

  • (Boolean)


46
47
48
# File 'lib/hoodoo/utilities/uuid.rb', line 46

def self.valid?( uuid )
  uuid.is_a?( ::String ) && ( uuid =~ MATCH_V4_UUID ) != nil
end