One thing I’ve always hated about working with Phoenix is the fact that I have to use strings to reference web request parameters in controllers. To any other developer, this might sound silly or even insane, but to my OCD-riddled brain, this is pure agony:
# web/controllers/some_controller.exdef show(conn, %{"id" => id}) do# do somethingendI guess I would’ve never even thought about using Atoms for parameters if I wasn’t already used to symbols in Rails:
params[:post][:title]To solve this “problem”, I’ve been using a custom plug in my Elixir applications for the past few months, that essentially symbolizes (or “atomizes”) all keys in the
params
map in controllers. After some input from other Elixir developers, and major security improvements, I published it as a package on Hex, calledBetterParams
, allowing you to do this:
def create(conn, %{id: id, post: %{title: title, body: body}}) do# or this: params[:post][:title]endImplementation uses
String.to_existing_atom
to prevent against Erlang atom table DoS attacks, and keeps the existing String keys so you can continue to use them if you want.Check out the project on Github.
continue reading on shyr.io
⚠️ This post links to an external website. ⚠️
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.