Created
May 24, 2023 16:38
-
-
Save Sija/eaf14e6ababc1a2f2c0ede7dc68c8f91 to your computer and use it in GitHub Desktop.
Presence protocol for Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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