Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: camelize when prefix is camelized already #343

Merged
merged 2 commits into from
Nov 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions lib/jsonapi/utils/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ defmodule JSONAPI.Utils.String do
iex> camelize("alreadyCamelized")
"alreadyCamelized"

iex> camelize("alreadyCamelized-id")
"alreadyCamelizedId"

iex> camelize("alreadyCamelized_id")
"alreadyCamelizedId"

iex> camelize("PascalLambda_id")
"pascalLambdaId"

"""
@spec camelize(atom) :: String.t()
def camelize(value) when is_atom(value) do
Expand All @@ -121,28 +130,27 @@ 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] ->
{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

defp camelize_list([]), do: []

defp camelize_list([h | t]) do
[String.capitalize(h)] ++ camelize_list(t)
[String.capitalize(h) | camelize_list(t)]
end

@doc """
Expand Down
Loading