Elixir:写入一个文件并创建 parent 个目录(如果它们不存在)——在一行中

Elixir: Write to a file and create parent directories if they don't exist - in one line

Elixir 中是否有一个函数可以:

目前我写过这样的功能,虽然比较 为每个我想写入文件的项目写这个不方便 parent 可能还不存在。

defp write_to_file(path, contents) do
  with :ok <- File.mkdir_p(Path.dirname(path)),
       :ok <- File.write(path, contents)
  do
    :ok
  end
end

最理想的情况是像这样的东西作为 Elixir 标准库的一部分存在,但是我找不到这样的东西

File.write(path, content, create_parents: true)

standard library 中绝无仅有。虽然为什么不这样做:

File.mkdir_p!(Path.dirname(path))
File.write(path, contents)

但是如果你想传递来自 mkdir 的错误,你可以像这样简化你的代码:

with :ok <- File.mkdir_p(Path.dirname(path)) do
  File.write(path, contents)
end