Current section

Files

Jump to
sigma_kit lib util.ex
Raw

lib/util.ex

defmodule SigmaKit.Util do
@doc """
Get a random string of given length.
Returns a random url safe encoded64 string of the given length.
Used to generate tokens for the various modules that require unique tokens.
"""
def random_string(length \\ 10) do
length
|> :crypto.strong_rand_bytes()
|> Base.url_encode64()
|> binary_part(0, length)
end
@doc """
Get a random numeric string of given length.
"""
def random_numeric_string(length \\ 10) do
length
|> :crypto.strong_rand_bytes()
|> :crypto.bytes_to_integer()
|> Integer.to_string()
|> binary_part(0, length)
end
@doc "Trim whitespace on either end of a string. Account for nil"
def trim(str) when is_nil(str), do: str
def trim(str) when is_binary(str), do: String.trim(str)
def blank?(term), do: Blankable.blank?(term)
@doc "Opposite of blank?"
def present?(term), do: !Blankable.blank?(term)
def pluralize(word, count), do: Inflex.inflect(word, count)
def format_money(cents, currency \\ "USD"), do: CurrencyFormatter.format(cents, currency)
@doc "Useful for when you have an array of strings coming in from a user form"
def trim_strings_in_array(array) do
array
|> Enum.map(&String.trim/1)
|> Enum.filter(&present?/1)
end
@doc """
## Examples:
iex> number_with_delimiter(1000)
"1,000"
iex> number_with_delimiter(1000000)
"1,000,000"
"""
def number_with_delimiter(i) when is_binary(i), do: number_with_delimiter(String.to_integer(i))
def number_with_delimiter(i) when is_integer(i) do
i
|> Integer.to_charlist()
|> Enum.reverse()
|> Enum.chunk_every(3, 3, [])
|> Enum.join(",")
|> String.reverse()
end
end