Elixir Function Guards

Sometimes, we’d like to have function calls depending on certain conditions, such as whether the role of a user is admin or just a mere peasant. This is where function guards come into play.

Let’s mock a login function:

def login(user) do
  ...
  retrieve_user_data(user)
  ...
end

The retrieve_user_data function would maybe load a collection of airplane tickets that the user can see; if the user is an admin, then they would see all the tickets in the system so that they can manage them, while a peasant would only see their purchased tickets. To achieve that, simply use guards:

defp retrieve_user_data(user) when user.role == 'admin' do
  #...all the tickets in the system
end
defp retrieve_user_data(user) when user.role == 'peasant' do
  #...just the peasant's tickets
end

Alexandra Docolin

Developer. React-Native worshipper. Please don't ask me about tests 😊

Tags
Elixir