Skip to content

Instantly share code, notes, and snippets.

@hassanshaikley
Last active June 21, 2021 20:19
Show Gist options
  • Save hassanshaikley/e43e71c6ecfa8ff268d45901b01fc478 to your computer and use it in GitHub Desktop.
Save hassanshaikley/e43e71c6ecfa8ff268d45901b01fc478 to your computer and use it in GitHub Desktop.
Messing with Elixir
# Usually with piping we do something like so
def get_user_with_account(id) do
user = case get_user_by_id(id) do
{:ok, user} ->
result = prepare_user(user)
{:ok, result}
error ->
error
end
end
defp prepare_user(%User{} = user) do
user_public_fields = Map.take(user, [:first_name, :last_name, :id])
other_user_data = %{
has_funding: account_has_funding?(user.account),
account_public: user.account.is_public
}
Map.merge(user_public_fields, other_user_data)
end
# But I am starting to wonder if something like this is nicer
# Pros:
# Fewer lines of Code
#
# Cons:
# It looks like it might be more resistant to change -- but I am not quite sure yet
# Will need function heads for the errors for every function you pipe through (but can this be made into an advantage)
#
def get_user_with_account(id) do
id
|> get_user_by_id
|> prepare_user
end
defp prepare_user({:error, _} = error), do: error
defp prepare_user({:ok, %User{} = user}) do
user_public_fields = Map.take(user, [:first_name, :last_name, :id])
other_user_data = %{
has_funding: account_has_funding?(user.account),
account_public: user.account.is_public
}
{:ok, Map.merge(user_public_fields, other_user_data)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment