I am looking for the best way of concatenating atoms, I have the following method:
String.to_atom("foo" <> Atom.to_string(:bar))
# :foobar
I am looking for the best way of concatenating atoms, I have the following method:
String.to_atom("foo" <> Atom.to_string(:bar))
# :foobar
It is not recommended to use String.to_atom because atoms are not garbage collected
One short way…
iex> :"foo#{:bar}"
:foobar
thanks but can you explain what you mean by that?
It means if You reach the atom’s limit, your application will stop working
There’s a limit to the number of atoms that an application can have - it’s not good to dynamically create them.
Here’s a relevant thread: Is this a correct way to avoid wasting or reaching the atom limit? - #16 by rvirding
This has the exact same problem as the code in the OP.
Therefore I’d advise against doing that as well!
The suggestion is to not generate atoms at runtime at all.
Yes it is the same problem… it was not meant to solve the problem of dynamic atom generation, just a shorter way to write bad code
it is actually present in the source code for ecto
:
lib/ecto/schema.ex
opts = Keyword.put_new(opts, :foreign_key, :"#{name}_id")
That specific code is called at compile time, not runtime though.