Reputation: 9859
I have a params
map and want to get the list of values who's "type" is %Plug.Upload{}
. How do I check for the type in Elixir?
Upvotes: 3
Views: 1182
Reputation: 222198
You can use the pattern %Plug.Upload{}
with for
as for
skips all the items that do not match the passed pattern.
This will return a list of all the files present in the values of the Map params
:
for {_, %Plug.Upload{} = file} <- params, do: file
If you just want to do something with the file, you can pass a block to do
:
for {_, %Plug.Upload{} = file} <- params do
IO.inspect file
end
Change _
to a variable name if you also want to access the file's name as present in the form that was submitted.
Upvotes: 0
Reputation: 71
params is a map, so Enum.filter gets key/value pairs, and the value is what will be a Plug.Upload, so:
params |> Enum.filter(fn({k, v}) -> match?(%Plug.Upload{}, v) end)
Upvotes: 0
Reputation: 23174
You can pattern match on structs just as you can on maps, so you can use Enum.filter
and Kernel.match?
:
params
|> Enum.filter(&match?(%Plug.Upload{}, &1))
Upvotes: 4