script
March 29, 2018, 7:50am
1
I have a list of maps like this:
some = [
%Plug.Upload{
content_type: "text/plain",
filename: "robots.txt",
path: "/tmp/plug-1522/multipart-1522309353-607768740397237-3"
},
%Plug.Upload{
content_type: "image/vnd.microsoft.icon",
filename: "favicon.ico",
path: "/tmp/plug-1522/multipart-1522309353-525002356217272-3"
}
]
This is stored in a some
. How can i access the atoms likecontent_type, file_name
e.t.c for both of these?
Thanks!
idi527
March 29, 2018, 7:52am
2
Maybe
Enum.map(some, fn %Plug.Upload{content_type: content_type, filename: filename} ->
{content_type, filename}
end)
It returns
[{"text/plain", "robots.txt"}, {"image/vnd.microsoft.icon", "favicon.ico"}]
script
March 29, 2018, 7:54am
3
I meant access them directly. through some like with some kernel function using dot
idi527
March 29, 2018, 7:55am
4
You have direct access to them inside Enum.map
's closure. What do you need to do with that data?
script
March 29, 2018, 8:04am
5
I have to check certain conditions like if the path_name
is valid and file
exists before saving the file . And I have multiple incoming files so I think i have to use comprehensions to loop through this array of maps check the condition and then save the file one by one.
idi527
March 29, 2018, 8:06am
6
I would use ecto changesets for validations. And then maybe filter out the invalid ones.
But if you don’t want to use changesets:
data =
some
|> Stream.map(fn upload -> validate(upload) end) # validate each upload
|> Stream.filter(fn {_upload, valid?} -> valid? end) # filter out "invalid" uploads
|> Enum.map(fn {upload, _valid?} -> Map.from_struct(upload) end) # turn upload structs into maps
Repo.insert_all("some_table", data) # insert all valid uploads
where
@spec validate(Plug.Upload.t) :: {Plug.Upload.t, valid? :: boolean}
defp validate(%Plug.Upload{path: path, filename: filename} = upload) do
valid? = valid_path?(path) && exists?(filename)
{upload, valid?}
end
1 Like