From b350ac8d15abe75b63555d35d9f1347f1dcd9c2e Mon Sep 17 00:00:00 2001 From: Dylan Fitzgerald Date: Mon, 2 Jan 2017 20:12:39 -0700 Subject: [PATCH] Make &stringify_keys/1 private. Since &keys_to_string/1 is public, also add a test case to coverage for &stringify_keys/1. Drop useless `stringify_keys(nil)` case. Continue intercepting %DateTime{} before it matches %{} --- lib/code_corps/map_utils.ex | 14 +++++++------- test/lib/code_corps/map_utils_test.exs | 7 ++++++- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/code_corps/map_utils.ex b/lib/code_corps/map_utils.ex index 154cb422f..c965da0e3 100644 --- a/lib/code_corps/map_utils.ex +++ b/lib/code_corps/map_utils.ex @@ -7,18 +7,18 @@ defmodule CodeCorps.MapUtils do def keys_to_string(map), do: stringify_keys(map) + # Intercept incoming %DateTime arguments; otherwise they will match %{} + defp stringify_keys(%DateTime{} = val), do: val # Goes through a list and stringifies keys of any map member - def stringify_keys(nil), do: nil - def stringify_keys(map = %{}) do + defp stringify_keys(map = %{}) do map |> Enum.map(fn {k, v} -> {stringify_key(k), stringify_keys(v)} end) |> Enum.into(%{}) end - def stringify_keys([head | rest]), do: [stringify_keys(head) | stringify_keys(rest)] + defp stringify_keys([head | rest]), do: [stringify_keys(head) | stringify_keys(rest)] # Default - def stringify_keys(not_a_map), do: not_a_map - - def stringify_key(k) when is_atom(k), do: Atom.to_string(k) - def stringify_key(k), do: k + defp stringify_keys(val), do: val + defp stringify_key(k) when is_atom(k), do: Atom.to_string(k) + defp stringify_key(k), do: k end diff --git a/test/lib/code_corps/map_utils_test.exs b/test/lib/code_corps/map_utils_test.exs index 881ae11b7..b4e6e8490 100644 --- a/test/lib/code_corps/map_utils_test.exs +++ b/test/lib/code_corps/map_utils_test.exs @@ -1,9 +1,14 @@ defmodule CodeCorps.MapUtilsTest do use ExUnit.Case, async: true - import CodeCorps.MapUtils, only: [rename: 3] + import CodeCorps.MapUtils, only: [keys_to_string: 1, rename: 3] test "&rename/3 renames old key in map to new key" do assert %{"foo" => 2} |> rename("foo", "bar") == %{"bar" => 2} end + + test "&keys_to_string/1 stringifies any keys in map" do + assert %{:a => "one", :b => "two"} |> keys_to_string == %{"a" => "one", "b" => "two"} + assert %{} |> keys_to_string == %{} + end end