presence v0.7.0 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. The functions are not automatically imported by Kernel.

Currently, these modules implements Presence protocol.

Summary

Functions

A value is blank if it’s 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 false, empty, or a whitespace string.

For example

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

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

List

[] is blank:

iex> is_blank([])
true

' ' is blank:

iex> is_blank(' ')
true

Map

%{} is blank:

iex> is_blank(%{})
true

String

A 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

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 = state.presence || country.presence || 'US'