Boolean parameters in routes

In the docs for Phoenix Routing we can see several examples such as below, where a parameter is a boolean.

Routes.user_path(Endpoint, :show, 17, admin: true, active: false)
"/users/17?admin=true&active=false"

Do we ever want to pass a boolean though? Because that will result in a string “true” and “false” in the URL, and in the controller action, we’ll have to convert “true” and “false” string respectively to true and false.

I was thinking to pass 1 or 0 like I used to do in PHP, to easily convert the parameter into a boolean, but converting 0 to a boolean gives true.

iex> !!0
true

Actually, while I’m writing this, I have the idea to use String.to_existing_atom/1

String.to_existing_atom("false")
String.to_existing_atom("true")

Do you do the same? Would maybe be interesting to have a plug that detects true and false strings for any route param (and query string param) and convert them automatically to the atoms? Systematically for all incoming requests.

I never use the strings “true” and “false” in these situations. But even if I did, you still have to convert anything coming to your controllers from string to the proper type – and also validate! – before acting on it. Doesn’t matter much if it’s the true/false or 1/0.

This is for you to decide but I wouldn’t. Make a Plug, sure, but use it selectively inside your controllers like so:

plug BooleanParameter, only: [:admin, :use_utc_time]

The above is used with crushing success and is practically one of the reasons for Phoenix being as good as it is (although there are many reasons).

1 Like