Skip to content

Instantly share code, notes, and snippets.

@Sija
Created May 24, 2023 16:38
Show Gist options
  • Save Sija/eaf14e6ababc1a2f2c0ede7dc68c8f91 to your computer and use it in GitHub Desktop.
Save Sija/eaf14e6ababc1a2f2c0ede7dc68c8f91 to your computer and use it in GitHub Desktop.
Presence protocol for Elixir
defprotocol Presence do
@doc "Determines whether the value is present and truthy"
def present?(data)
end
defimpl Presence, for: Atom do
def present?(false), do: false
def present?(nil), do: false
def present?(_), do: true
end
defimpl Presence, for: [Integer, Float] do
def present?(_), do: true
end
defimpl Presence, for: BitString do
def present?(""), do: false
def present?(string), do: String.trim(string) != ""
end
defimpl Presence, for: URI do
def present?(%URI{}), do: false
def present?(_), do: true
end
defimpl Presence, for: [List, Keyword] do
def present?([]), do: false
def present?(_), do: true
end
defimpl Presence, for: Tuple do
def present?({}), do: false
def present?(_), do: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment