presence v0.8.5 Presence protocol

The Presence protocol is responsible for checking the presence of a value.

The functions required to be implemented are is_blank/1, is_present/1 and presence/1. These functions are not automatically imported by Kernel.

Currently, these modules implements Presence protocol.

Summary

Functions

A value is blank if it’s nil, false, empty, or a whitespace string

A value is present if it’s not blank

Returns the value if it’s present otherwise returns nil

Types

t()
t() :: term

Functions

is_blank(value)

A value is blank if it’s nil, false, empty, or a whitespace string.

For example

  • nil
  • false
  • []
  • ''
  • ' '
  • %{}
  • {}
  • ""
  • " "

are all blank.

This simplifies

!address || Enum.empty?(address)

to

is_blank(address)

Examples

Atom

nil is blank:

iex> is_blank(nil)
true

false is blank:

iex> is_blank(false)
true

:false atom is blank:

iex> is_blank(:false)
true

BitString

A bit string (or simply string) is blank if it’s empty or contains whitespaces only:

iex> is_blank("")
true

iex> is_blank("   ")
true

iex> is_blank("\t\n\r")
true

iex> is_blank(" blah ")
false

Unicode whitespace is supported:

iex> is_blank("\u00a0")
true

Float

1.1 is not blank:

iex> is_blank(1.1)
false

Integer

1 is not blank:

iex> is_blank(1)
false

List

[] is blank:

iex> is_blank([])
true

' ' is blank:

iex> is_blank(' ')
true

Map

%{} is blank:

iex> is_blank(%{})
true

Tuple

{} is blank:

iex> is_blank({})
true
is_present(value)

A value is present if it’s not blank.

presence(value)

Returns the value if it’s present otherwise returns nil.

presence(value)

is equivalent to

is_present(value) ? value : nil

For example, something like

if is_present(state), do: state = state
if is_present(country), do: country = country

region  = state || country || "US"

becomes

region = presence(state) || presence(country) || "US"