File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -129,4 +129,35 @@ defmodule Phoenix.Naming do
129129
130130 bin |> String . replace ( "_" , " " ) |> String . capitalize
131131 end
132+
133+ @ doc """
134+ Converts an attribute/form field into its titleized version (all words capitalized).
135+
136+ ## Examples
137+
138+ iex> Phoenix.Naming.titleize(:username)
139+ "Username"
140+ iex> Phoenix.Naming.titleize(:created_at)
141+ "Created At"
142+ iex> Phoenix.Naming.titleize("user_id")
143+ "User"
144+
145+ """
146+ @ spec titleize ( atom | String . t ) :: String . t
147+ def titleize ( atom ) when is_atom ( atom ) ,
148+ do: titleize ( Atom . to_string ( atom ) )
149+ def titleize ( bin ) when is_binary ( bin ) do
150+ bin =
151+ if String . ends_with? ( bin , "_id" ) do
152+ binary_part ( bin , 0 , byte_size ( bin ) - 3 )
153+ else
154+ bin
155+ end
156+
157+ bin
158+ |> String . replace ( "_" , " " )
159+ |> String . split ( )
160+ |> Enum . map ( & String . capitalize / 1 )
161+ |> Enum . join ( " " )
162+ end
132163end
Original file line number Diff line number Diff line change @@ -42,4 +42,20 @@ defmodule Phoenix.NamingTest do
4242 assert Naming . camelize ( "_foo_bar" , :lower ) == "fooBar"
4343 assert Naming . camelize ( "foo_bar_1" , :lower ) == "fooBar1"
4444 end
45+
46+ test "humanize/1 converts atoms and strings to humanized form" do
47+ assert Naming . humanize ( :username ) == "Username"
48+ assert Naming . humanize ( :created_at ) == "Created at"
49+ assert Naming . humanize ( "user_id" ) == "User"
50+ assert Naming . humanize ( "foo_bar" ) == "Foo bar"
51+ assert Naming . humanize ( :email_id ) == "Email"
52+ end
53+
54+ test "titleize/1 converts atoms and strings to titleized form" do
55+ assert Naming . titleize ( :username ) == "Username"
56+ assert Naming . titleize ( :created_at ) == "Created At"
57+ assert Naming . titleize ( "user_id" ) == "User"
58+ assert Naming . titleize ( "foo_bar" ) == "Foo Bar"
59+ assert Naming . titleize ( :email_id ) == "Email"
60+ end
4561end
You can’t perform that action at this time.
0 commit comments