chad-adams

chad-adams

Loading of atoms which have been defined in a module's types

I have a simple struct which has a status field which can be :active, :idle, or nil. Definition looks like here:

defmodule Event do
  defstruct status: nil

  @type t :: %__MODULE__{
          status: nil | :active | :idle
        }
end

Then I have an application which parses JSON representation to create instances of these structs. As part of this, I am calling String.to_existing_atom/1. So "active" from the JSON becomes :active. However, I am getting ArgumentError from String.to_existing_atom/1 due to the atom not being loaded yet.

I have tried Jose’s solution on this github thread whereby Code.ensure_loaded?/1 is called to force loading of the module. But in this case, although the module gets loaded, the atoms here are defined in the module’s typing so it doesn’t appear to create them.

Any suggestions on a clean way to solve this?

Marked As Solved

brettbeatty

brettbeatty

In my opinion the better alternative to String.to_existing_atom/1 is to be explicit about which values you’ll cast. For example, if you’re creating an Event struct from a string-keyed map (like parsed JSON), it could look something like this:

def new(map) do
  %__MODULE__{
    ... # other fields
    status: cast_status(map["status"])
  }
end

defp cast_status("active"), do: :active
defp cast_status("idle"), do: :idle
defp cast_status(nil), do: nil

This particular example would raise if you got an unacceptable value back from the JSON. If you need to validate the input, something like Ecto changesets would do the trick too. Or if it fit your needs you could just make everything else nil.

Also Liked

NobbZ

NobbZ

Types and Specs are not available at runtime, and therefore have no effects like creating atoms.

You need to actually use those atoms in your code.

mudasobwa

mudasobwa

Creator of Cure

The sole purpose of String.to_existing_atom/1 would be to raise if the atom is not existing. If you are sure that the source of string in the question is trustful, there is not much sense in using it in general, if the atom already exists, it would be used, atoms are never re-created.

So, AFAICT, this is an XY problem and the simplest although cleanest solution would be to resort to String.to_atom/1 unless you expect values to come from the outside; in that case, it’d be better to handle wrong values in a bit more sophisticated manner.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement