Access atoms inside list of plugmap

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!

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"}]

I meant access them directly. through some like with some kernel function using dot

You have direct access to them inside Enum.map's closure. What do you need to do with that data?

I have to check certain conditions like if the path_nameis 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.

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