URL [Slug Generator] With Elixir

URL [Slug Generator] With Elixir

   

   

Learn how to build a human-readable, search engine-friendly URL slugs generator with Elixir.

Step 1:

Create a new Elixir project by going to the command line and typing the following in your desired directory:

$ mix new slug_generator && cd slug_generator

Step 2:

Open your test file test/slug_generator_test.exs, remove the autogenerated test and add the following test:

  test "generates slug" do
    s = "[\"Pattern\", \"Matching\", \"In\", \"Elixir\"] = [a, b, c, d]"

    assert "pattern-matching-in-elixir-a-b-c-d" = SlugGenerator.create(s)
  end

  test "generates simple slug" do
    s = "My slug generator & simple test "

    assert "my-slug-generator-and-simple-test" = SlugGenerator.create(s)
  end

Watch your tests fail by going to the command line and running the test by typing mix test.

Step 3:

Let's make our test pass by opening our main project file lib/slug_generator.ex, remove the autogenerated hello world function and add the following:

  def create(string) do
    string
    |> String.downcase()
    |> String.replace(~r/[^a-zA-Z0-9 &]/, "")
    |> String.replace("&", "and")
    |> String.split()
    |> Enum.join("-")
  end

Go back to the command line and watch your tests pass with no failures by typing mix test.

Code Breakdown

String.downcase(string)

Makes everything lowercase.

String.replace(subject, pattern, replacement)

We use it twice, the first is used with a regular expression as a pattern to replace everything that is not alphanumeric or the & symbol in the string with nothing or an empty string. The second time used with the & symbol as a pattern to get replaced with and.

String.split(string)

Returns a list of substrings ignoring whitespace.

Enum.join(list, joiner)

Joins the list of substrings with the - symbol and returns a string.

Conclusion

That's a short and sweet way to build a URL slug generator with Elixir, using the useful String module combined with the Enum module. You could get way fancier and add more functionality but that should do it for this example tutorial. Thank you so much for your time, I really appreciate it.

   

Join The Elixir Army