Skip to content

Commit

Permalink
Fix snake_cased_map_keys not ignoring structs
Browse files Browse the repository at this point in the history
  • Loading branch information
ZelvaMan committed Oct 29, 2023
1 parent 9792cd4 commit bd27ac1
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
7 changes: 6 additions & 1 deletion lib/simplificator_3000/map_helpers.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
defmodule Simplificator3000.MapHelpers do
alias Simplificator3000.StringHelpers
# TODO fix inconsistent behavion
# camel cased map keys converts almost all struct to map, because its used to convert result to json response
# but snake_cased_map_keys is used to convert user input to snake case, so it should not convert structs to maps

def camel_cased_map_keys(%DateTime{} = val), do: val

Expand All @@ -25,7 +28,9 @@ defmodule Simplificator3000.MapHelpers do

def camel_cased_map_keys(val), do: val

def snake_cased_map_keys(%{} = map) do
def snake_cased_map_keys(struct = %_{}), do: struct

def snake_cased_map_keys(map) when is_map(map) do
for {key, val} <- map, into: %{} do
{StringHelpers.underscore(key), snake_cased_map_keys(val)}
end
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule Simplificator3000.MixProject do
def project do
[
app: :simplificator_3000,
version: "0.5.4",
version: "0.5.5",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
name: "Simplificator3000",
Expand Down
36 changes: 36 additions & 0 deletions test/simplificator_3000/map_helpers_test.exs
Original file line number Diff line number Diff line change
@@ -1,4 +1,40 @@
defmodule Simplificator3000.MapHelpersTest do
use ExUnit.Case
doctest Simplificator3000.MapHelpers

test "snake case map keys" do
struct = %{
"camelCase" => "camelCase",
"Snake_case" => "snake_case",
"snake_case" => %{
"camelCase" => "camelCase",
"snake_case" => "snake_case"
}
}

expected = %{

Check warning on line 15 in test/simplificator_3000/map_helpers_test.exs

View workflow job for this annotation

GitHub Actions / test

key "snake_case" will be overridden in map
"camel_case" => "camelCase",
"snake_case" => "snake_case",
"snake_case" => %{
"camel_case" => "camelCase",
"snake_case" => "snake_case"
}
}

assert Simplificator3000.MapHelpers.snake_cased_map_keys(struct) == expected
end

test "dont break structs" do
input = %File.Stat{
access: :read,
size: 12345
}

expected = %File.Stat{
access: :read,
size: 12345
}

assert Simplificator3000.MapHelpers.snake_cased_map_keys(input) == expected
end
end

0 comments on commit bd27ac1

Please sign in to comment.