dokicro
Map key is a atom or string
Hi,
I am new to elixir and here is part of the code I dont like
slider = case Map.has_key?(attrs, :slider_id) do
true -> get_slider!(attrs.slider_id)
false -> get_slider!(attrs["slider_id"])
end
Reason for this is because when I do attrs = Map.put(attrs, :slider_id, slider.id) in sliders_test map key is atom
But when I do the same thing in slider_controller_test map key is string.
Most Liked
LostKobrakai
Params in contollers have string keys because anybody can send you any param and creating an atom for those would be a attack vector to crash the vm. It’s still generally adviced to work with atom keys in your business part of the app and to sanitize and atomize params before passing things forward into it.
kokolegorille
You could…
slider = Map.get(attrs, :slider_id) || Map.get(attrs, "slider_id")
As a rule of thumb, expect data coming from outside to be “key”, and after cast to be :key.
Nicd
To elaborate a bit, the reason why map keys from external sources (like user input) are strings, is that atoms are not garbage collected and there is a set maximum amount of atoms available in the system. If you exceed that amount, the VM will crash. So that’s why you shouldn’t create atoms from user input for example.








