Pipes are great for operations that can't fail and all of them always will be carried. In case you want to stop the pipeline, you can't. You would have to write functions like this:
maybe_repo_update(nil), do: nil
maybe_repo_update(data), do: Repo.update(data)
To solve that problem there is a new special form in Elixir 1.2 called with
. It can stop the pipeline at the moment where something doesn't match:
with changeset <- cast(model, params, ~w(something), ~w())
{:ok, changeset} <- conditional_operation(changeset)
{:ok, model} <- Repo.insert(changeset)
This will make sure that if conditional operation returns something else than {:ok, changeset}
it will not try to run the last repo insert. In Elixir 1.3 you can also use else
part.
However for changesets it is more common to use solution suggested by @JustMichael:
def conditional(changeset) do
if something_to_do do
transform(changeset)
else
changeset
end
end
This solution will always run the Repo.update
part.
conditional
is either a function or nil? – Adamec