Skip to content

Instantly share code, notes, and snippets.

@seancribbs seancribbs/reduce.ex
Created Mar 10, 2019

Embed
What would you like to do?
# This function is only included for context - it creates a multi-operation transaction structure
# for a single widget and its associated options
def create_multi(params, operation_type, widget, identifier \\ :widget) do
changeset = Widget.changeset(widget, params)
apply(Ecto.Multi, operation_type, [Ecto.Multi.new(), identifier, changeset])
|> maybe_merge_widget_options(identifier, params)
end
# Here's the usage of reduce. Notice the map + "mappend"(?) inside the reduce. If Ecto.Multi
# implemented Collectable, this would be a ripe opportunity for Enum.into/2...
def create_bulk_multi(widgets) do
Enum.reduce(widgets, Ecto.Multi.new(),
fn widget, multi_acc ->
unique_key = unique_multi_key(:widget)
widget_multi = create_multi(widget, :insert, %Widget{}, unique_key)
Ecto.Multi.append(multi_acc, widget_multi)
end
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.