In a case
statement in Elixir, is it possible to do nothing if a particular condition is met in a case
statement? Or must something always be returned?
To illustrate, here's a snippet from a Phoenix app that I'm working on:
Enum.map(record_params, fn(record_id) ->
record = Repo.get!(Record, record_id)
case Repo.update(record) do
{:ok, struct} ->
# I DON'T REALLY NEED ANYTHING TO HAPPEN HERE... BUT I HAVE TO HAVE A CLAUSE TO MATCH WHEN THE UPDATE RETURNS {:ok, struct}
IO.inspect struct
{:error, changeset} ->
errors = parse_errors(changeset)
IO.inspect errors
json(conn |> put_status(400), %{status: "error", message: "There was a problem updating this record.", errors: errors})
end
end)
If the record
is updated, I need to know if there's an error, get information about it, and return that to the client, hence the need for the case
statement... but I don't really need to do anything if the record has been updated successfully - {:ok, struct}
. Since these updates are taking place inside an Enum.map()
, if the update is successful, I just want the map to continue to loop through the record_ids
.
For the time being, I've just been putting IO.inspect struct
in the success condition - this is harmless, but not really necessary. I'd prefer to clean up my code, if possible. I can't remove the {:ok, struct}
condition due to Elixir's pattern matching, and if I put nothing at all under that condition, I get the error syntax error before: '->'
.
Now I am totally new to Elixir (and the functional programming paradigm, in general), so if there is a more 'Elixirish' way to handle this sort of scenario, I would love to hear about it.
json
multiple times here. Also, how are you handling the response for when all updates succeed? - Dogbert