DIW
Generating alphanumeric strings for permalinks
I want to create random alphanumeric permalinks that I can be sure are always unique. Is there a library in Elixir for doing something like this, or does anyone know how it could be implemented?
Most Liked
idi527
Yeah, I usually do something like
@spec permalink(integer) :: binary
def permalink(bytes_count) do
bytes_count
|> :crypto.strong_rand_bytes()
|> Base.url_encode64(padding: false)
end
permalink(15)
#=> "tWW9pID24daLP_Q4emyd"
9
Aetherus
IMHO, if you want perfect uniqueness, you have to sacrifice randomness. I’ve written a module for myself, it generates alphanumeric ID’s based on a 48-bit timestamp, a 32-bit node name hash code, and a 16-bit sequence number.
defmodule CUID do
@moduledoc """
CUID is for **Cluster-Unique ID**. It's shorter than UUID, case sensitive, and URL-safe.
The generated ID is guaranteed to be unique among the BEAM cluster
if there are no more than 65536 nodes in the cluster,
and the request rate is lower than 256 req/(node * millisec).
## Examples
iex> CUID.start_link(CUID)
iex> CUID.gen(CUID)
"AWAAtXL1doYA"
"""
use Agent
use Bitwise
@doc """
Start a `CUID` process linked to the current process.
"""
def start_link(name) do
case Agent.start_link(fn -> 0 end, name: name) do
{:error, {:already_started, _}} -> :ignore
other -> other
end
end
@doc """
Generate a CUID.
"""
def gen(server) do
now = System.os_time(:millisecond) # 48 bits
node_name_hash = Node.self() |> Atom.to_charlist() |> Enum.reduce(0, fn(char, hash) ->
((hash <<< 5) - hash + char) &&& 0xFFFF
end) # 32 bits
n = Agent.get_and_update(server, fn n -> {n, (n + 1) &&& 0xFF} end) # 16 bits
<<now::48, node_name_hash::16, n::8>> |> Base.url_encode64(padding: false)
end
end
5
AlchemistCamp
The standard library is the gift that keeps giving! Isn’t Elixir the greatest?
5
Popular in Questions
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
If I have a post route which an argument:
post /my_post_route/:my_param1, MyController.my_post_handler
How would get the post params ...
New
Hello all!
I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Hello, how can I check the Phoenix version ?
Thanks !
New
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
I have followed this StackOverflow post to install the specific version of Erlang.
And When I am running mix ecto.setup then getting fol...
New
i’m a new one to elixir
which editor can i use
vs code? or atom?
Thanks! :smiley:
New
Hi! May someone helps me, please!
I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
How to handle excepions in elixir?
Suppose i have A, B, C ,D, E modules. and each module has get() function.
A.get() method will call t...
New
I would like to know what is the best IDE for elixir development?
New
Other popular topics
Hello!
tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability.
After spen...
New
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
New
Hey,
Just curious what are the main benefits of Elixir compared to Clojure?
When is Elixir more useful than Clojure and vice versa?
Th...
New
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this:
...
New
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
Hello!
Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1]
15:22:35.803 [error] gen_event {lager_file_backend...
New
Hi everyone!
I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









