Skip to content

Commit

Permalink
feat: add function serialization support
Browse files Browse the repository at this point in the history
- Added support for function serialization in
`ensure_json_serializable/1`.

- Functions are now converted to JSON by capturing their module, name,
and arity.

- Anonymous functions are labeled as "anonymous function" in the output
for clarity.
  • Loading branch information
subaru9 committed Sep 9, 2024
1 parent 9e2b91c commit 1ed739a
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions lib/error_message/serializer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ defmodule ErrorMessage.Serializer do
end

def to_jsonable_map(%ErrorMessage{code: code, message: message, details: details}) do
if Logger.metadata[:request_id] do
if Logger.metadata()[:request_id] do
%{
code: code,
message: message,
request_id: Logger.metadata[:request_id],
request_id: Logger.metadata()[:request_id],
details: ensure_json_serializable(details)
}
else
Expand Down Expand Up @@ -65,7 +65,7 @@ defmodule ErrorMessage.Serializer do

defp ensure_json_serializable(%struct{} = struct_data) do
%{
struct: struct |> Kernel.to_string |> String.replace("Elixir.", ""),
struct: struct |> Kernel.to_string() |> String.replace("Elixir.", ""),
data: struct_data |> Map.from_struct() |> ensure_json_serializable
}
end
Expand All @@ -77,13 +77,38 @@ defmodule ErrorMessage.Serializer do
end

defp ensure_json_serializable(details) when is_tuple(details) do
details |> Tuple.to_list |> ensure_json_serializable
details |> Tuple.to_list() |> ensure_json_serializable
end

defp ensure_json_serializable(fun) when is_function(fun) do
case :erlang.fun_info(fun, :module) do
{:module, :erl_eval} ->
build_function_metadata(:erl_eval, "anonymous function", fun)

{:module, module} ->
{:name, name} = :erlang.fun_info(fun, :name)

module
|> Kernel.to_string()
|> String.replace("Elixir.", "")
|> build_function_metadata(name, fun)
end
end

defp ensure_json_serializable(value) do
value
end

defp build_function_metadata(module, function_name, fun) do
{:arity, arity} = :erlang.fun_info(fun, :arity)

%{
module: module,
function: function_name,
arity: arity
}
end

defp local_pid?(pid) do
node(pid) === node()
end
Expand Down

0 comments on commit 1ed739a

Please sign in to comment.