Skip to content

Instantly share code, notes, and snippets.

@Tsugami
Last active May 18, 2021 04:05
Show Gist options
  • Save Tsugami/230ae19229904e516eb02d52b533b632 to your computer and use it in GitHub Desktop.
Save Tsugami/230ae19229904e516eb02d52b533b632 to your computer and use it in GitHub Desktop.
defmodule AliasesRegistry do
@moduledoc false
def init do
Registry.start_link(keys: :unique, name: __MODULE__)
end
def via do
{:via, Registry, {__MODULE__, :aliases_registry}}
end
def register(command_name, [head | tail]) when is_binary(command_name) do
cond do_register(command_name, head) do
:ok -> register(command_name, tail)
rest -> rest
end
end
def register(command_name, _) when is_binary(command_name) do
do_register(command_name, command_name)
end
defp do_register(command_name, command_alias) when is_binary(command_name) and is_binary(command_alias) do
case Registry.register(__MODULE__, command_alias, command_name) do
{:ok, _} -> :ok
{:error, reason, _} -> {:error, reason}
end
end
def get_command_name(str) when is_binary(str) do
case Registry.lookup(__MODULE__, str) do
[{_pid, command_name}] -> command_name
_ -> nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment