Skip to content

Commit

Permalink
Fix bug where underscore/dasherize misses single characters
Browse files Browse the repository at this point in the history
  • Loading branch information
protestContest authored and mattpolzin committed Feb 23, 2024
1 parent 2edf707 commit f3db97d
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/jsonapi/utils/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ defmodule JSONAPI.Utils.String do
iex> underscore("corgiAge")
"corgi_age"
iex> underscore("ages-0-17")
"ages_0_17"
"""
@spec underscore(String.t()) :: String.t()
def underscore(value) when is_binary(value) do
value
|> String.replace(~r/([a-zA-Z\d])-([a-zA-Z\d])/, "\\1_\\2")
|> String.replace(~r/(?<=[a-zA-Z\d])-(?=[a-zA-Z\d])/, "_")
|> String.replace(~r/([a-z\d])([A-Z])/, "\\1_\\2")
|> String.downcase()
end
Expand Down Expand Up @@ -65,6 +68,9 @@ defmodule JSONAPI.Utils.String do
iex> dasherize("_top__posts_")
"_top__posts_"
iex> dasherize("ages_0_17")
"ages-0-17"
"""
@spec dasherize(atom) :: String.t()
def dasherize(value) when is_atom(value) do
Expand All @@ -75,7 +81,7 @@ defmodule JSONAPI.Utils.String do

@spec dasherize(String.t()) :: String.t()
def dasherize(value) when is_binary(value) do
String.replace(value, ~r/([a-zA-Z0-9])_([a-zA-Z0-9])/, "\\1-\\2")
String.replace(value, ~r/(?<=[a-zA-Z0-9])_(?=[a-zA-Z0-9])/, "-")
end

@doc """
Expand Down

0 comments on commit f3db97d

Please sign in to comment.