So far my Elixir journey has focused more on independent features of the language and less about real app construction. The next 15/20 days will be a bit different because I'm now ready to apply everything I've learned in hopes of going deeper. With each iteration I'll be adding something new or improving some functionality from a previous post.
The application itself will be simple and much less the focus of this series as you might imagine. The url shortener has a small api surface area and offers enough (primitive) "real world" requirements that it should make for a great learning playground.
Part 1: mix new
The first step is to run `mix new` from the command line. This will scaffold everything we need to kickstart a simple project in Elixir.
mix new example
Before we dive into building the web interface or anything to make this concurrent I first wanted to write the most basic module required. Start by adding a module called `Shortener`. In this module we will first implement a function called `create_short_url` that is responsible for inserting the url and hash (alias). Next implement a function called `get_url` that is responsible for retrieving the url given some hash (alias).
defmodule Shortener do
def new(), do: %{}
def create_short_url(state, hash, url) do
Map.put(state, hash, url)
end
def get_url(state, hash) do
Map.get(state, hash, :undefined)
end
end
To see this in action we next write a unit test to exercise the 2 functions together. You can run this from the command line using `mix test`.
defmodule ShortenerTest do
use ExUnit.Case, async: true
setup do
Shortener.new()
end
test "create will add key/value given url and hash", state do
assert Shortener.get_url(state, "x") === :undefined
new_state = Shortener.create_short_url(state, "x", "google.com")
assert Shortener.get_url(new_state, "x") === "google.com"
end
end
Note: the state returned from `setup` is made available to each unit test as `state` just before the `do`
To play around with this module in IEx run this command `iex -S mix run`
state = Shortener.new()
new_state = Shortener.create_short_url(state, "x", "google.com")
Shortener.get_url(new_state, "x")
You can track my progress on github commit by commit. If you just want the code for this post checkout this commit.