Access atoms inside list of plugmap

I have a list of maps like this:

 some  =   [
   content_type: "text/plain",
  filename: "robots.txt",
  path: "/tmp/plug-1522/multipart-1522309353-607768740397237-3"
  content_type: "image/",
  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?

Maybe, fn %Plug.Upload{content_type: content_type, filename: filename} ->
  {content_type, filename}

It returns

[{"text/plain", "robots.txt"}, {"image/", "favicon.ico"}]

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

You have direct access to them inside'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 = 
  |> upload -> validate(upload) end) # validate each upload
  |> Stream.filter(fn {_upload, valid?} -> valid? end) # filter out "invalid" uploads
  |> {upload, _valid?} -> Map.from_struct(upload) end) # turn upload structs into maps

Repo.insert_all("some_table", data) # insert all valid uploads


@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?}
1 Like