From d5d0b80a890a82a67a70fbc9e84a776390b2bfa2 Mon Sep 17 00:00:00 2001 From: Victor Rodrigues Date: Mon, 28 Oct 2024 16:57:52 +0100 Subject: [PATCH 1/2] 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 """ From 8c480c504c116dfa9ff00abf854bff6a1a52a972 Mon Sep 17 00:00:00 2001 From: Victor Rodrigues Date: Fri, 1 Nov 2024 12:00:17 +0100 Subject: [PATCH 2/2] fix regression when first word is pascal casing --- lib/jsonapi/utils/string.ex | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/jsonapi/utils/string.ex b/lib/jsonapi/utils/string.ex index a8d36b6e..206f730e 100644 --- a/lib/jsonapi/utils/string.ex +++ b/lib/jsonapi/utils/string.ex @@ -115,6 +115,9 @@ defmodule JSONAPI.Utils.String do iex> camelize("alreadyCamelized_id") "alreadyCamelizedId" + iex> camelize("PascalLambda_id") + "pascalLambdaId" + """ @spec camelize(atom) :: String.t() def camelize(value) when is_atom(value) do @@ -138,7 +141,9 @@ defmodule JSONAPI.Utils.String do # If there are multiple words, perform the camelizing [h | t] -> - Enum.join([h | camelize_list(t)]) + {first_character, rest_word} = String.split_at(h, 1) + first_word = String.downcase(first_character) <> rest_word + Enum.join([first_word | camelize_list(t)]) end end