sztosz

sztosz

How to ensure atom exists?

I have in module a very long list of filters like this:

@mapping %{
    published_at: {:date_time, "published_at"},
    indexed_at: {:date_time, "indexed_at"},
    ...
    not_parent_shared_uid: {:terms_exclusion, "parent.shared_uid"},
    ...
    }

Because I wan’t to dynamically call some functions like this

  def parse_filter({filter_name, value}, topic_id, acc) do
    {function, field} = Map.get(@mapping, String.to_existing_atom(filter_name))
    apply(__MODULE__, function, [value, field, topic_id, acc])
  end

Yet for existing atoms in @mapping I sometimes, occasionally get

Elixir.ArgumentError in :erlang.binary_to_existing_atom/2
arg0: "not_parent_shared_uid"
arg1: :utf8

So the question is, how can I make sure that those atoms do exist?

Marked As Solved

NobbZ

NobbZ

Are you sure, that the string does not contain any unprintable bytes (zero width space or similar)?

But instead of relying on String.to_existing_atom/1, I’d use something like this:

@mapping %{...}

@filter_name_to_atom @mapping |> Enum.map(fn {atom, _} -> {to_string(atom), atom} end) |> Enum.into(%{})

  def parse_filter({filter_name, value}, topic_id, acc) do
    {function, field} = Map.get(@mapping, @filter_name_to_atom[filter_name])
    apply(__MODULE__, function, [value, field, topic_id, acc])
  end

Or if you need the crash on invalid filter names use Map.fetch!/2 instead of Access-Syntax.


edit

Using Map.fetch!/2 had actually the benefit that we would also fail for "ok", while String.to_existing_atom("ok") fould simply return :ok.

Also Liked

idi527

idi527

Maybe you can replace your map with a “function lookup”. And have mappings keys be strings? Would it change anything?

defmodule SomeModule do
  @moduledoc ""
  
  mappings = %{
    "published_at" => {:date_time, "published_at"},
    "indexed_at" => {:date_time, "indexed_at"},
    "not_parent_shared_uid" => {:terms_exclusion, "parent.shared_uid"}
  }

  @spec lookup_mapping(String.t()) :: {atom, String.t()} | nil
  defp lookup_mapping(filter_name)

  Enum.map(mappings, fn {filter_name, value} ->
    defp lookup_mapping(unquote(filter_name)) do
      unquote(value) # would create :date_time and :terms_exclusion atoms during compilation
    end
  end)

  defp lookup_mapping(_unmatched), do: nil

  def parse_filter({filter_name, value}, topic_id, acc) do
    case lookup_mapping(filter_name) do
      {function, field} ->
        apply(__MODULE__, function, [value, field, topic_id, acc])
      nil -> 
        acc
    end
  end
end
sztosz

sztosz

@idi527: I’d rather use atoms as map keys, although it’s just a personal preference. But I’ll look more into your code, thanks :slight_smile:

I can’t be sure, it comes from the outside. It’s not really something I can control, I have to have “good faith” in the maintainer of the app that’s queering this app of mine. He’s got no malicious intent, though, as he’s a my work colleague.

With Map.fetch! this would fail every time exactly where it should, so I may go with this instead. Thanks :slight_smile:

Where Next?

Popular in Questions Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
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 39297 209
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement