Sumit Kumar Arora
Sumit Kumar Arora

Reputation: 75

How to generate non-random UUID based on string in ruby?

As we have multi threaded environment in ruby so need to generate every time same UUID like 9f54c0ae-f9cf-46ba-985d-637e1dcc0e5d base on same input string JOB_userId_jobId like JOb_1_90.

Example: "JOb_1_96"=>"412ce9ff-fb47-4b8e-94c9-4bd37481cb4b", "JOb_1_97"=>"7232e1d6-422e-4d49-a47f-f4628e4ffd57", "JOb_1_98"=>"de932dbd-76e4-4828-8bc1-cebd8254db61", "JOb_1_99"=>"ce1e91a3-8d5d-47f8-9dc6-58790cbb98e9", ....

Any help would be appreciated.Thanks

Upvotes: 6

Views: 3139

Answers (1)

kolen
kolen

Reputation: 2842

As I understand, UUIDs should not be random, but based on input string. This is known as "version 3" and "version 5" UUIDs. These versions differ by hashing function used: MD5 vs SHA1. See rfc4122, section 4.3.

If you don't mind including Activesupport dependency to your project (it's quite large gem, but popular and included in Rails), then you can use its uuid_v3 and uuid_v5 methods.

require "active_support/core_ext/digest/uuid"
puts Digest::UUID.uuid_v3("ae279f4c-6327-47c6-b53c-05a3f10dd0c6", "bar")
puts Digest::UUID.uuid_v5("ae279f4c-6327-47c6-b53c-05a3f10dd0c6", "bar")

Output (note that it's the same on each run, unlike random UUIDs):

fab2e5c9-bf64-39d4-bc17-e72ccdb013aa
15c252d7-fd16-52de-aac2-223a58aa6ea9

Upvotes: 10

Related Questions