Deference (Deference v1.0.0)

Copy Markdown View Source

A function deferring library inspired by zig!

import Deference

def example() do
  with_defer do

    {:ok, user_id} =
      API.User.create("really_cool_username", "really_cool_password")

    err_defer do
      API.User.delete("really_cool_username")
    end

    post_id =
      API.Post.create("really_cool_username", "hello")
      |> case do
        {:ok, post_id} -> post_id
        {:error, _reason} ->
          # can't post, no reason to keep the user around
          throw_err({:error, :failed_to_post})
      end

    err_defer do
      API.Post.delete(post_id)
    end

    API.Post.edit(post_id, "hello
edit: wow i didn't expect this to blow up")
      |> case do
      {:ok, post_id} -> :ok
      {:error, _reason} ->
        # failed to edit post, bail!
        throw_err({:error, :failed_to_edit_post})
    end

  end
end

See the Github page for more examples

Summary

Functions

Defer an expression to run after any exiting with_defer/1 under any condition, error or not.

Defer an expression to run after any exiting with_defer/1 by either an exception or via throw_err/1

Stop function execution and run all deferred functions, returns the provided value or :error by default

Start a new deferral block

Functions

defer(list)

(macro)

Defer an expression to run after any exiting with_defer/1 under any condition, error or not.

err_defer(list)

(macro)

Defer an expression to run after any exiting with_defer/1 by either an exception or via throw_err/1

throw_err(value \\ :error)

(macro)

Stop function execution and run all deferred functions, returns the provided value or :error by default

This function must be within a with_defer/1 block.

with_defer(clauses)

(macro)

with_defer(opts, clauses)

(macro)

Start a new deferral block

rescue may also be used for exception handling:

with_defer do
  ...
rescue
  _ -> :ok
end