From 32185848371072cab1a404b80fb9b1ecea33bbf9 Mon Sep 17 00:00:00 2001 From: Michael Guarino Date: Wed, 9 Aug 2017 21:04:32 -0400 Subject: [PATCH] properly underscore types --- cereal_ex.iml | 9 +++++++++ lib/cereal/utils.ex | 28 +++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 cereal_ex.iml diff --git a/cereal_ex.iml b/cereal_ex.iml new file mode 100644 index 0000000..cb272eb --- /dev/null +++ b/cereal_ex.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/lib/cereal/utils.ex b/lib/cereal/utils.ex index 71c8d5b..5de6a0d 100644 --- a/lib/cereal/utils.ex +++ b/lib/cereal/utils.ex @@ -10,7 +10,7 @@ defmodule Cereal.Utils do |> List.last() |> String.replace("Serializer", "") |> String.replace("View", "") - |> String.downcase() + |> underscore() end @doc """ @@ -43,4 +43,30 @@ defmodule Cereal.Utils do defp deep_merge_relationship_paths(left, right), do: Keyword.merge(left, right, &deep_merge_relationship_paths/3) defp deep_merge_relationship_paths(_, left, right), do: deep_merge_relationship_paths(left, right) + + + @doc false + def underscore(""), do: "" + def underscore(<>) do + <> <> do_underscore(t, h) + end + + defp do_underscore(<>, _) when h in ?A..?Z and not (t in ?A..?Z or t == ?.) do + <> <> do_underscore(rest, t) + end + defp do_underscore(<>, prev) when h in ?A..?Z and not prev in ?A..?Z do + <> <> do_underscore(t, h) + end + defp do_underscore(<>, _) do + <> <> underscore(t) + end + defp do_underscore(<>, _) do + <> <> do_underscore(t, h) + end + defp do_underscore(<<>>, _) do + <<>> + end + + defp to_lower_char(char) when char in ?A..?Z, do: char + 32 + defp to_lower_char(char), do: char end