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 bug where underscore/dasherize misses single characters #316

Merged
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
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
Loading