I’d love for Ecto.Repo.get or get_by to return a {:ok, foobar} tuples. I could use it in with conditionals for cleaner more idiomatic Elixir.
Here’s my function:
def can_list_bots?(team_id, user_id) do
team = Repo.get(Team, team_id)
user = Repo.get_by(User, id: user_id, team_id: team_id)
if team != nil && user != nil do
"admin" in user.roles
else
false
end
end
Is there any way to make this code more idiomatic that I’m not seeing?
def can_list_bots?(team_id, user_id) do
team = Repo.get(Team, team_id)
user = team && Repo.get_by(User, id: user_id, team_id: team_id)
if user do
"admin" in user.roles
else
false
end
end
or if you want with
def can_list_bots?(team_id, user_id) do
with team when not is_nil(team) <- Repo.get(Team, team_id),
user when not is_nil(user) <- Repo.get_by(User, id: user_id, team_id: team_id) do
"admin" in user.roles
else
_ -> false
end
end
or with with pattern matches
def can_list_bots?(team_id, user_id) do
with %Team{} <- Repo.get(Team, team_id),
%User{roles: roles} <- Repo.get_by(User, id: user_id, team_id: team_id) do
"admin" in roles
else
_ -> false
end
end
You can also do it in a single sql query. Probably.
Slightly off topic but do you really need to fetch the team at all? It seems like if you can assume that a team exists if the user has that team_id then you don’t need to fetch the team at all.