Let's use a custom Elixir function combined with the Faker Elixir library to generate automatic fake usernames data.
Step 1:
This is for learning purposes only so let's create a new simple Elixir project by going to the command line and typing the following in your desired directory:
$ mix new fake_username && cd fake_username
Step 2:
Go to the website https://hex.pm and search for the faker library to grab the latest version, so you can copy that to your mix config file, at the time of the making of this tutorial the latest version is 0.17.0, add the following to your project dependencies inside your mix.exs
file:
{:faker, "~> 0.17.0"}
Then in the command line type in $ mix deps.get
to fetch your new dependency.
Step 3:
Open your test file test/fake_username_test.exs
, remove the autogenerated test and add the following test:
test "generates a username" do
name = " My Long Random Username "
assert FakeUsername.get(name) == "mylongrandomusername"
end
Go to your command line and run the test by typing mix test
the test should fail of course because we haven't created the function get()
in our module.
Step 4:
Open your main project file lib/fake_username.ex
, remove the autogenerated hello world function and add the following function:
def get(name) do
name
|> String.downcase()
|> String.split()
|> Enum.join()
end
Go to the command line and run the test again mix test
now it should pass with no failures.
Code Breakdown
String.downcase() will make all letters lowercase.
String.split() it will return a list of all words after every whitespace, ignoring trailing and leading whitespace.
Enum.join() will join all the words in our previously created list with String.split() and return a single string.
Manual Testing
To test it out manually go to the command line and type in iex -S mix
.
iex> FakeUsername.get(Faker.Person.name())
Conclusion
That's all folks, now every time that we call our function FakeUsername.get() passing in a random name with Faker.Person.name() function from the Faker library we get a string back with no whitespace that can be used as a username, we could get fancy and add random numbers and symbols to our returned string in our custom function.
Top comments (0)