Skip to content
Open
Show file tree
Hide file tree
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
30 changes: 30 additions & 0 deletions lib/phoenix/naming.ex
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,34 @@ defmodule Phoenix.Naming do

bin |> String.replace("_", " ") |> String.capitalize
end

@doc """
Converts an attribute/form field into its titleized version (all words capitalized).

## Examples

iex> Phoenix.Naming.titleize(:username)
"Username"
iex> Phoenix.Naming.titleize(:created_at)
"Created At"
iex> Phoenix.Naming.titleize("user_id")
"User"

"""
@spec titleize(atom | String.t) :: String.t
def titleize(atom) when is_atom(atom),
do: titleize(Atom.to_string(atom))
def titleize(bin) when is_binary(bin) do
bin =
if String.ends_with?(bin, "_id") do
binary_part(bin, 0, byte_size(bin) - 3)
else
bin
end
Comment on lines +150 to +155
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the API could be similar to one provided in Rails? https://apidock.com/rails/String/humanize
(I mean the keep_id_suffix part)


bin
|> String.replace("_", " ")
|> String.split()
|> Enum.map_join(" ", &String.capitalize/1)
end
end
16 changes: 16 additions & 0 deletions test/phoenix/naming_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,20 @@ defmodule Phoenix.NamingTest do
assert Naming.camelize("_foo_bar", :lower) == "fooBar"
assert Naming.camelize("foo_bar_1", :lower) == "fooBar1"
end

test "humanize/1 converts atoms and strings to humanized form" do
assert Naming.humanize(:username) == "Username"
assert Naming.humanize(:created_at) == "Created at"
assert Naming.humanize("user_id") == "User"
assert Naming.humanize("foo_bar") == "Foo bar"
assert Naming.humanize(:email_id) == "Email"
end

test "titleize/1 converts atoms and strings to titleized form" do
assert Naming.titleize(:username) == "Username"
assert Naming.titleize(:created_at) == "Created At"
assert Naming.titleize("user_id") == "User"
assert Naming.titleize("foo_bar") == "Foo Bar"
assert Naming.titleize(:email_id) == "Email"
end
end
Loading