View Source UnionTypespec (union_typespec v0.0.4)

A simple, tiny, compile time-only library for defining an Elixir @type whose values are one of a fixed set of options.

Summary

Functions

Transforms an enumerable (like a list of atoms) into an AST for use in a typespec.

Unquote on the right-hand side of @type if you prefer the explicitness of that syntax over the union_type macro.

Same as UnionTypespec.union_type/1 but for a private type (@typep).

Functions

Link to this macro

union_type(arg)

View Source (since 0.0.1) (macro)

Transforms an enumerable (like a list of atoms) into an AST for use in a typespec.

This is primarily useful when you have a module attribute that defines

Taken wholesale from Eiji's ElixirForum answer.

Example:

defmodule MyModule do
  import UnionTypespec, only: [union_type: 1]

  @permissions [:view, :edit, :admin]
  union_type permission :: @permissions

  @spec random_permission() :: permission()
  def random_permission, do: Enum.random(@permissions)
end
Link to this function

union_type_ast(list)

View Source (since 0.0.1)

Unquote on the right-hand side of @type if you prefer the explicitness of that syntax over the union_type macro.

Example:

defmodule MyModule do
  @permissions [:view, :edit, :admin]
  @type permission :: unquote(UnionTypespec.union_type_ast(@permissions))

  @spec random_permission() :: permission()
  def random_permission, do: Enum.random(@permissions)
end
Link to this macro

union_typep(arg)

View Source (since 0.0.3) (macro)

Same as UnionTypespec.union_type/1 but for a private type (@typep).

Example:

defmodule MyModule do
  import UnionTypespec, only: [union_typep: 1]

  @permissions [:view, :edit, :admin]
  union_typep permission :: @permissions

  @spec random_permission() :: permission()
  defp random_permission, do: Enum.random(@permissions)
end