Elixir pattern matching - capitalising text

How could I use pattern matching to capitalize the input below? Is there a more Elixir way of doing this?

  def show(conn, %{"messenger" => messenger}) do
    text = String.capitalize(messenger)
    render conn, "show.html", messenger: text
  end

Regards,

Rich

In my opinion capitalization is a display property and not a data property and as such should happen in the template and not in the controller.

You only alter the presentation not the meaning.

3 Likes

Very good point @NobbZ. I was about to explain that you are not just capitalizing the map of params, but also transforming it in a keyword list, which is a very different thing. :wink:

But @NobbZ point is really better, and you should listen to him! :wink:

1 Like

I am putting this in conversation about capitalization because up until today I was always doing this in my Phoenix HTML templates to achieve capitalization of every word:

<div>
 <%= :something_to_display |> humanize() |> String.split(" ") |> Enum.map(&String.capitalize/1) |> Enum.join(" ") %>
</div>

and I only just realized how foolish I am being. As @NobbZ says, it’s a “display property”. I should be using CSS!

<div style="text-transform: capitalize">
  <%= humanize(:something_to_display) %>
</div>

or with TailwindCSS:

<div class="capitalize">
  <%= humanize(:something_to_display) %>
</div>
2 Likes