@@ -83,14 +83,12 @@ defmodule Upload.Multi do
83
83
84
84
## Example
85
85
86
- ```elixir
87
- defp insert_person(changeset) do
88
- Ecto.Multi.new()
89
- |> Ecto.Multi.insert(:person, changeset)
90
- |> Upload.Multi.handle_changes(:upload_avatar, :person, changeset, :avatar, key_function: &key_function/1)
91
- |> Repo.transaction()
92
- end
93
- ```
86
+ defp insert_person(changeset) do
87
+ Ecto.Multi.new()
88
+ |> Ecto.Multi.insert(:person, changeset)
89
+ |> Upload.Multi.handle_changes(:upload_avatar, :person, changeset, :avatar, key_function: &key_function/1)
90
+ |> Repo.transaction()
91
+ end
94
92
95
93
## Options
96
94
@@ -99,6 +97,7 @@ defmodule Upload.Multi do
99
97
"""
100
98
def handle_changes ( multi , name , subject , changeset , field , opts \\ [ ] ) do
101
99
key_function = key_function_from_opts ( opts )
100
+ validate_function = validate_function_from_opts ( opts )
102
101
103
102
Multi . run ( multi , name , fn repo , changes ->
104
103
# This code is run after the record in inserted in the Multi pipeline.
@@ -120,6 +119,7 @@ defmodule Upload.Multi do
120
119
key_function . ( record )
121
120
end
122
121
)
122
+ |> validate_function . ( field )
123
123
124
124
record_changeset . changes
125
125
|> Enum . reduce ( Ecto.Multi . new ( ) , fn { changed_field , change } , multi ->
@@ -130,11 +130,25 @@ defmodule Upload.Multi do
130
130
|> repo . transaction ( )
131
131
|> case do
132
132
{ :ok , result } -> { :ok , result [ "#{ field } _attach_blob" ] }
133
- error -> error
133
+ { : error, _stage , changeset , _rest } -> { : error, changeset }
134
134
end
135
135
end )
136
136
end
137
137
138
+ defp validate_function_from_opts ( opts ) do
139
+ case Keyword . get ( opts , :validate ) do
140
+ nil ->
141
+ fn changeset , _field -> changeset end
142
+
143
+ validate_function when is_function ( validate_function , 2 ) ->
144
+ validate_function
145
+
146
+ unexpected ->
147
+ raise ArgumentError ,
148
+ "validate function must be a function of arity 2. Got #{ inspect ( unexpected ) } "
149
+ end
150
+ end
151
+
138
152
defp key_function_from_opts ( opts ) do
139
153
case Keyword . get ( opts , :key_function ) do
140
154
nil ->
0 commit comments