String.to_atom errors
- Dominant language
- Elixir
- Stars
- 1.7k
- Forks
- 112
- PR merge metrics
- No merged PRs in 30d
Description
If you are liberal with where you are calling [`String.to_atom`](https://hexdocs.pm/elixir/String.html#to_atom/1) you should be weary that:
"Currently Elixir does not support the conversion of strings that contain Unicode codepoints greater than 0xFF."
That means that if you run `String.to_atom` on a string containing a `’` mark (for instance), it will error.
To fix this, when converting to an atom you could convert all of these quote marks to valid `'` marks and filter out everything else that would cause an error.
You could write the following:
```elixir
@doc """
iex>safe_to_atom("hi’hi")
:"hi'hi"
iex> safe_to_atom("hello")
:"hello"
"""
def safe_to_atom(string) when is_binary(string) do
string
|> String.replace("’", "'")
|> String.to_charlist
|> Enum.filter(&(&1 <= 255))
|> to_string
|> String.to_atom
end
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.