Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Ecto: Could someone give an example of Ecto.Multi.run/5

Tags:

elixir

ecto

The docs state

run(t, name, module, function, args) :: t when function: atom, args: [any]

Similar to run/3, but allows to pass module name, function and arguments. The function should return either {:ok, value} or {:error, value}, and will receive changes so far as the first argument (prepened to those passed in the call to the function).

But I'm unsure how to use this. Let's say I have this function I want to run inside of Ecto.Multi:

def some_fun(value, other_value) do
  case value do
    nil -> {:error, other_value}
    _ -> {:ok, other_value}
  end
end

How would that work?

like image 206
Ole Spaarmann Avatar asked Dec 23 '22 23:12

Ole Spaarmann


1 Answers

I'm assuming you want value to be the "changes so far" and other_value is a value you're specifying when calling Multi.run/5. In that case, if your function is in a module named Foo:

defmodule Foo do
  def some_fun(value, other_value) do
    case value do
      nil -> {:error, other_value}
      _ -> {:ok, other_value}
    end
  end
end

then your Multi.run/5 call will be:

Multi.run(multi, name, Foo, :some_fun, [other_value])

which is equivalent to the following Multi.run/3 call:

Multi.run(multi, name, fn value -> Foo.some_fun(value, other_value) end)
like image 197
Dogbert Avatar answered Jan 17 '23 17:01

Dogbert