source: unsplash.com

How Rails generates UUIDs by extending the digest library

An overview of the UUID specification and the Digest::UUID module

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

What’s a UUID?

UUID stands for Universally Unique IDentifier — also known as GUID (Globally Unique IDentifier).

It’s a sequence of bits used to ensure identification of a unique resource.

A UUID is 128 bits long, and can guarantee uniqueness across space and time.

There is currently 5 versions of UUIDs.

They are known as version 1, 2, 3, 4 and 5.

Each version implements a set of variations more or less complex.

For example, the UUID v1 specification is based on date-time and MAC address.

On the other hand, the UUID v4 specification defines a set of 122 bits randomly generated.

As you noticed, each version defines its own way to generate the UUID.

Feel free to browse the RFC 4122 for further information about each version.

Now that we’re more familiar with the notion of UUID, let’s see how Ruby on Rails extends the digest library to implement the versions 3, 4 and 5 of the UUID specification.

The Digest::UUID module

This module provides a set of helper methods to generate UUIDs for the versions 3, 4 and 5 – as defined in the RFC 4122 specification

In the above example, we use the uuid_v3 , uuid_v4 and uuid_v5 methods to generate UUIDs.

These 3 methods respectively return a UUID v3, UUID v4 and UUID v5.

The uuid_v4 method simply uses the return value of SecureRandom.uuid .

Indeed, as defined in the UUID v4 specification, 122 bits are randomly generated.

So, this specification is already implemented by the SecureRandom.uuid method.

Now, the UUID v3 and UUID v5 specifications are almost similar.

They are composed in a mix of a namespace and a name that are encrypted using the MD5 algorithm (UUID v3) or the SHA-1 algorithm (UUID v5).

All this logic in encapsulated in the uuid_from_hash method that is internally called by both the uuid_v3 and uuid_v5 methods.

The uuid_from_hash method takes 3 arguments:

the encryption algorithm (MD5 or SHA-1)

the namespace

the name

So when we call

Internally the uuid_v3 method calls the uuid_from_hash method with the following arguments

As defined in the specification, the UUID version 3 uses the MD5 algorithm to generate the hash.

For uuid_v5

As defined in the specification, the UUID version 5 uses the SHA-1 algorithm to generate the hash.

Voilà!

ONE MORE THING ⬇

Feel free to subscribe here: www.rubycademy.com