benonymus

benonymus

Enum.reduce refactor with multi

Hey there,

I have this function:

  defp add_same_price(order, ids) do
    filtered_order_book = get_incomplete_orders(ids, order.command)

    same_price_orders =
      filtered_order_book
      |> Enum.filter(fn x -> Decimal.cmp(x.price, order.price) == :eq and x.id != order.id end)

    summed_order =
      Enum.reduce(same_price_orders, order, fn x, acc ->
        amount_sum = Decimal.add(x.amount, acc.amount)

        LimitOrder.changeset_update_amount_completed(x, %{completed: true, amount: x.amount})
        |> Repo.update()

        Map.put(acc, :amount, amount_sum)
      end)

    LimitOrder.changeset_update_amount_completed(order, %{
      completed: summed_order.completed,
      amount: summed_order.amount
    })
    |> Repo.update()
  end

This works well, but I think that doing the transaction inside the reduce is not great, because this way if the last transaction fails the previous ones wont be rolled back.
How can I refactor this using multi?
Usually when I use multi that is my acc, but i need the result of this reduce function as well.
I think that if i would just have the multi as my acc here too, i’d need to update the order, that happens as the last thing currently, inside the reduce as well, and then get(how?) it from the multi. Is this in the good direction? Thoughts?

Marked As Solved

LostKobrakai

LostKobrakai

If you need results of previous steps consider Ecto.Multi.run and Ecto.Multi.merge. Those should give you options to do what you need to do.

Edit: Maybe I’ve misunderstood the question a bit. Your reduce function can hold any value, so it can hold a multi struct and the summed amouns:

Enum.reduce(orders, %{order: order, multi: multi}, fn x, %{order: order, multi: multi} -> 
  # To stuff
  %{order: order, multi: multi}
end)

Also Liked

LostKobrakai

LostKobrakai

  %{order: summed_order, multi: multi} =
    Enum.reduce(same_price_orders, %{order: order, multi: Multi.new()}, fn x, acc ->
      amount_sum = Decimal.add(x.amount, acc.order.amount)

      changeset =
        LimitOrder.changeset_update_amount_completed(x, %{
          completed: true,
          amount: x.amount
        })

      %{
        order: Map.put(acc.order, :amount, amount_sum),
        multi: Multi.update(acc.multi, x.id, changeset)
      }
    end)

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement