Current section

Files

Jump to
manganese_core_kit lib core_kit.ex
Raw

lib/core_kit.ex

defmodule Manganese.CoreKit do
@doc """
Similar to `Macro.underscore` but with different handling of numbers in strings.
For example, take the string `"asset3d"`. `Macro.underscore` returns simply `"asset3d". `underscore_key/1` returns `"asset_3d"` for consistency with the Foreverdaunt codebase when de/serializing JSON.
"""
@spec underscore_key(binary | atom | integer) :: binary
def underscore_key(integer) when is_integer(integer), do: underscore_key Integer.to_string integer
def underscore_key(atom) when is_atom(atom), do: underscore_key Atom.to_string atom
def underscore_key(string) when is_binary(string) do
string = Macro.underscore(string)
string = Regex.replace(~r/([a-z]\d)/, string, fn _, pair -> "#{String.at(pair, 0)}_#{String.at(pair, 1)}" end)
string
end
end