Skip to content

Commit

Permalink
[TOOL-564] Add detuple/1 to Utils
Browse files Browse the repository at this point in the history
  • Loading branch information
PhiMed committed Mar 11, 2024
1 parent 74a1888 commit 8e2c5a7
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
23 changes: 23 additions & 0 deletions lib/airbrake/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,27 @@ defmodule Airbrake.Utils do
do: {k, @filtered_value},
else: {k, filter(v, filtered_attributes)}
end

@doc """
Turns tuples into lists for JSON serialization of Airbrake payloads.
"""
def detuple(struct) when is_struct(struct) do
struct |> Map.from_struct() |> detuple()
end

def detuple(map) when is_map(map) do
Enum.into(map, %{}, fn {k, v} -> {detuple(k), detuple(v)} end)
end

def detuple(list) when is_list(list) do
Enum.map(list, &detuple/1)
end

def detuple(tuple) when is_tuple(tuple) do
tuple |> Tuple.to_list() |> detuple()
end

def detuple(other) do
other
end
end
34 changes: 32 additions & 2 deletions test/airbrake/utils_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ defmodule Airbrake.UtilsTest do

alias Airbrake.Utils

@moduletag :focus

defmodule Struct do
defstruct [:baz, :qux]
end
Expand Down Expand Up @@ -48,4 +46,36 @@ defmodule Airbrake.UtilsTest do
}
end
end

describe "detuple/1" do
test "returns a map when input is a struct" do
input = %Struct{baz: 100, qux: 200}

assert Utils.detuple(input) == %{baz: 100, qux: 200}
end

test "returns the original data when input is a map" do
input = %{baz: 100, qux: 200}

assert Utils.detuple(input) == input
end

test "returns the original data when input is a list" do
input = ["foo", "bar"]

assert Utils.detuple(input) == input
end

test "returns a list when input is a tuple" do
input = {:ok, "something"}

assert Utils.detuple(input) == [:ok, "something"]
end

test "returns the original value when the input is anything else" do
input = "something"

assert Utils.detuple(input) == input
end
end
end

0 comments on commit 8e2c5a7

Please sign in to comment.