From d5d0b80a890a82a67a70fbc9e84a776390b2bfa2 Mon Sep 17 00:00:00 2001 From: Victor Rodrigues Date: Mon, 28 Oct 2024 16:57:52 +0100 Subject: [PATCH] fix: camelize when prefix is camelized already --- lib/jsonapi/utils/string.ex | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/lib/jsonapi/utils/string.ex b/lib/jsonapi/utils/string.ex index 4f3d1cfd..a8d36b6e 100644 --- a/lib/jsonapi/utils/string.ex +++ b/lib/jsonapi/utils/string.ex @@ -109,6 +109,12 @@ defmodule JSONAPI.Utils.String do iex> camelize("alreadyCamelized") "alreadyCamelized" + iex> camelize("alreadyCamelized-id") + "alreadyCamelizedId" + + iex> camelize("alreadyCamelized_id") + "alreadyCamelizedId" + """ @spec camelize(atom) :: String.t() def camelize(value) when is_atom(value) do @@ -121,28 +127,25 @@ defmodule JSONAPI.Utils.String do def camelize(value) when value == "", do: value def camelize(value) when is_binary(value) do - with words <- - Regex.split( - ~r{(?<=[a-zA-Z0-9])[-_](?=[a-zA-Z0-9])}, - to_string(value), - trim: true - ) do - case words do - # If there is only one word, leave it as-is - [word] -> - word - - # If there are multiple words, perform the camelizing - [h | t] -> - Enum.join([String.downcase(h) | camelize_list(t)]) - end + case Regex.split( + ~r{(?<=[a-zA-Z0-9])[-_](?=[a-zA-Z0-9])}, + to_string(value), + trim: true + ) do + # If there is only one word, leave it as-is + [word] -> + word + + # If there are multiple words, perform the camelizing + [h | t] -> + Enum.join([h | camelize_list(t)]) end end defp camelize_list([]), do: [] defp camelize_list([h | t]) do - [String.capitalize(h)] ++ camelize_list(t) + [String.capitalize(h) | camelize_list(t)] end @doc """