Zoonk.Helpers (Zoonk v0.1.0-dev)
View SourceProvides helper functions for the Zoonk application.
Summary
Functions
Retrieves a changeset from a transaction result.
Conditionally puts a key-value pair into a map.
Remove accents from a string.
Converts a string to an existing atom.
Decodes a URL-safe Base64 encoded token and applies a function to the decoded result.
Functions
Retrieves a changeset from a transaction result.
Examples
iex> get_changeset_from_transaction({:ok, %{user: user}}, :user)
{:ok, %User{}}
iex> get_changeset_from_transaction({:error, :user, changeset, _}, :user)
{:error, %Ecto.Changeset{}}
Conditionally puts a key-value pair into a map.
Returns the map unchanged if the value is nil
or an empty string.
Otherwise, adds the key-value pair to the map.
Examples
iex> maybe_put(%{}, "key", "value")
%{"key" => "value"}
iex> maybe_put(%{"existing" => "data"}, "key", "value")
%{"existing" => "data", "key" => "value"}
iex> maybe_put(%{}, "key", nil)
%{}
iex> maybe_put(%{}, "key", "")
%{}
Remove accents from a string.
Examples
iex> remove_accents("Café")
"Cafe"
iex> remove_accents("Crème brûlée")
"Creme brulee"
iex> remove_accents("naïve")
"naive"
Converts a string to an existing atom.
Returns nil
if the atom doesn't exist instead of raising an error.
Examples
iex> to_existing_atom("catalog")
:catalog
iex> to_existing_atom("non_existent_atom")
nil
iex> to_existing_atom(nil)
nil
Decodes a URL-safe Base64 encoded token and applies a function to the decoded result.
This helper is useful for handling encoded tokens in authentication flows, particularly for session tokens that need to be decoded before use.
Parameters
token
- The Base64 URL-encoded token stringfun
- A function to apply to the successfully decoded tokenerror_value
- The value to return on decoding error (default::error
)
Returns
- The result of applying
fun
to the decoded token if decoding is successful error_value
if the token cannot be decoded
Examples
iex> with_decoded_token("c29tZV90b2tlbg==", &String.upcase/1)
"SOME_TOKEN"
iex> with_decoded_token("invalid+token", &String.upcase/1)
:error
iex> with_decoded_token("invalid+token", &String.upcase/1, nil)
nil