View Source Tmp (Tmp v0.3.0)

Temporary directories that are monitored and automatically removed.

Usage

Define your Tmp module:

defmodule MyApp.Tmp do
  use Tmp
end

Or with a custom base directory:

defmodule MyApp.CustomTmp do
  use Tmp, base_dir: "/path/to/custom/base/dir"
end

Add it to your supervision tree:

children = [
  {MyApp.Tmp, name: MyApp.Tmp}
]

Use it in your code:

MyApp.Tmp.dir(fn tmp_dir_path ->
  _my_file_path = Path.join(tmp_dir_path, "my_file")
  # do work with my_file_path...
  # then return a value
  {:ok, :foobar}
end)

You can also override the base directory for a specific call:

MyApp.Tmp.dir(fn tmp_dir_path ->
  # ...
end, base_dir: "/path/to/another/base/dir")

Summary

Functions

Creates a temporary directory and passes the path to the given function.

Functions

Link to this function

dir(module, function, options \\ [])

View Source
@spec dir(module(), function(), keyword()) :: term()

Creates a temporary directory and passes the path to the given function.

function runs in a new linked GenServer process. The directory is automatically removed when the function returns or the process terminates.

Options

  • :base_dir - The directory where the temporary directory will be created. Defaults to System.tmp_dir(). This directory serves as the parent directory and won't be removed when the function returns. Only the newly created temporary directory within :base_dir will be cleaned up.

  • :prefix - A string to prefix the temporary directory name. This can be useful for identifying the purpose or origin of the temporary directory.

  • :timeout - How long the function is allowed to run before the GenServer call terminates, defaults to :infinity

Examples

MyApp.Tmp.dir(fn tmp_dir_path ->
  :ok = Path.join(tmp_dir_path, "my_new_file") |> File.touch()
  1 + 1
end)