Creating UUIDs in Elixir

12,520

Solution 1

import Ecto

uuid = Ecto.UUID.generate

Solution 2

If you're using elixir with ecto, you can always use Ecto.UUID https://hexdocs.pm/ecto/Ecto.UUID.html

Solution 3

The canonical way to generate a globally unique reference in Elixir is with make_ref/0.

From the documentation:

Returns an almost unique reference.

The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes.

Solution 4

If you don't want to include Ecto in your project, you should evaluate https://github.com/zyro/elixir-uuid

defp deps do
  [ { :elixir_uuid, "~> 1.2" } ]
end
iex> UUID.uuid1()
"5976423a-ee35-11e3-8569-14109ff1a304"
iex> UUID.uuid3(:dns, "my.domain.com")
"03bf0706-b7e9-33b8-aee5-c6142a816478"

iex> UUID.uuid3("5976423a-ee35-11e3-8569-14109ff1a304", "my.domain.com")
"0609d667-944c-3c2d-9d09-18af5c58c8fb"
Share:
12,520

Related videos on Youtube

Jodimoro
Author by

Jodimoro

Updated on July 23, 2022

Comments

  • Jodimoro
    Jodimoro over 1 year

    What's a canonical way to generate UUIDs in Elixir? Should I necessarily use the library https://hex.pm/packages/uuid or is there a built-in library? I better have less dependencies and do more work than vise versa, therefore if I can generate in Elixir with an external dependency, it'll better go with it.

    • BenD
      BenD almost 7 years
      Why do you need to produce UUIDs? There are simpler built-in ways to generate unique keys/identifiers for things if you don't actually require true UUIDs.
    • cdegroot
      cdegroot almost 7 years
      :rand.uniform(), for example. Integer.to_string(:rand.uniform(4294967296), 32) <> Integer.to_string(:rand.uniform(4294967296), 32) will give you a 64 bit random identifier in base64 (don't get more than 32 bits or so out of rand.uniform - so if you need the full 128 bits, do four calls and string them together)
  • Kociamber
    Kociamber almost 5 years
    Not every Elixir project uses DB and Ecto mate.