∴ikura

Simple slug generator

One of the often-used patterns in web
development is generating a quasi-random
string. These are great for creating
‘slugs’ as often seen in URL shorteners,
& in this mobile-friendly age, passing
around small URLs is obligatory due
to the limitations of small screens &
SMS.

In Erlang, we are going to write a small
module called ‘slug.erl’ which can handle
all of this. Our home-spun module will
yield a quasi-random string of characters
& with that, we can let our imagination
run wild with what to do with the results.

Preppin’

Before we open an editor, let’s lay out
a few of the goals for what our code
should do:

The API should be flexible in generating slugs of a given length;

For UX purposes, we don’t want any slug to contain the zero or capital oh characters — they look the same on some screens after all;

Our code should make a valiant effort to generate solid randomness.

With that small specification in place, we should be good to
take a stab at it.

Code

Our slug should incorporate a range of characters, and
although there are a plethora of ways to accomplish this,
there’s nothing wrong with being pedantic about it and
just list them all out by hand.

With that concession made, here’s the first few lines
of our new module, ‘slug.erl’ :

If you take a close look, you’ll notice that our macro does
not include our forbidden characters (by design, of course).

Moving along, we next need to implement new/1. First off,
it will have to seed a random value; a set of integers which
gets stored via rand:seed/n in the calling process’s ‘process
dictionary.’ We use the ‘crypto’ module to generate the randomness,
though this may be overkill for some.