Nex.Utils (nex_core v0.4.3)

Copy Markdown

Shared utility functions used across the Nex framework.

This module contains common functions that are used by multiple modules to avoid code duplication.

Summary

Functions

Generates a cryptographically secure random hex string.

Generates a cryptographically secure random token.

Normalizes a module name into a dotted Elixir module string.

Safely converts a string to an existing atom.

Safely converts a module name string to an existing module.

Functions

generate_hex(length)

@spec generate_hex(pos_integer()) :: String.t()

Generates a cryptographically secure random hex string.

Examples

iex> Nex.Utils.generate_hex(16)
"abc123..."

generate_token(length \\ 24)

@spec generate_token(pos_integer()) :: String.t()

Generates a cryptographically secure random token.

Examples

iex> Nex.Utils.generate_token()
"abc123..."

normalize_module_name(module_name)

@spec normalize_module_name(module() | String.t()) :: String.t()

Normalizes a module name into a dotted Elixir module string.

Examples

iex> Nex.Utils.normalize_module_name(MyApp.Pages.Index)
"MyApp.Pages.Index"

iex> Nex.Utils.normalize_module_name("Elixir.MyApp.Pages.Index")
"MyApp.Pages.Index"

safe_to_existing_atom(string)

@spec safe_to_existing_atom(String.t()) :: {:ok, atom()} | :error

Safely converts a string to an existing atom.

Returns {:ok, atom} if the atom exists, or :error if it doesn't. This prevents atom exhaustion attacks by only converting atoms that have already been defined.

Examples

iex> Nex.Utils.safe_to_existing_atom("Phoenix")
{:ok, Phoenix}

iex> Nex.Utils.safe_to_existing_atom("NonExistentModule")
:error

safe_to_existing_module(module_name)

@spec safe_to_existing_module(module() | String.t()) :: {:ok, module()} | :error

Safely converts a module name string to an existing module.

Returns {:ok, module} if the module is loaded, or :error if not.

Examples

iex> Nex.Utils.safe_to_existing_module("Nex.Handler")
{:ok, Nex.Handler}

iex> Nex.Utils.safe_to_existing_module("Non.Existent")
:error