defmodule AtomTest do
use ExUnit.Case
test "to_existing_atom/1" do
value = "atom_that_does_not_exist"
new_atom = String.to_existing_atom(value)
assert new_atom == :atom_that_does_not_exist
end
end
mix test
1) test to_existing_atom/1 (AtomTest)
test/atom_test.exs:25
** (ArgumentError) errors were found at the given arguments:
* 1st argument: not an already existing atom
code: new_atom = String.to_existing_atom("atom_that_does_not_exist")
stacktrace:
:erlang.binary_to_existing_atom("atom_that_does_not_exist", :utf8)
test/atom_test.exs:27: (test)
E caso ele já tenha sido criado, não teremos problemas
lib/atom_test.exs
defmodule AtomTest do
use ExUnit.Case
# ...
test "atom that does exist" do
_atom = :atom_that_does_exist
value = "atom_that_does_exist"
new_atom = String.to_existing_atom(value)
assert new_atom == :atom_that_does_exist
end
end
mix test
........
Finished in 0.02 seconds (0.00s async, 0.02s sync)
5 tests, 0 failures
Conclusão
Atoms são muito utilizados no mundo elixir, são práticos e fáceis de usar. Vimos que precisamos tomar cuidado com a geração dinâmica e que podemos controlar o que pode ser criado. Mais a frente utilizaremos cada vez mais atoms para simplificar nosso código e estrutura-lo.