Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elixir constantize a string to get the module (String.to_module/1)?

I'm storing some metadata in a session to access different modules based on a string.

Is there any way to do this?

String.to_module("MyApp.Vendor")   #=> MyApp.Vendor
String.to_module("MyApp.Customer") #=> MyApp.Customer

Then end goal is using the account_type to look up the Struct by id to do something specific to that type.

account = Repo.get(String.to_module(account_type), account_id)
do_something_with(account)

def do_something_with(%Customer{id: id}) do 
  # yada yada
end

def do_something_with(%Vendor{id: id}) do 
  # something else
end
like image 929
daino3 Avatar asked Sep 15 '25 08:09

daino3


1 Answers

You are going to want to use String.to_existing_atom.

iex(5)> a = String.to_existing_atom("Elixir.Enum")
Enum
iex(6)> apply(a, :reverse, [[1, 2, 3]])

Note that the Elixir. prefix is important. If you do not include that, the system will not know what you are looking for.

like image 110
Justin Wood Avatar answered Sep 18 '25 10:09

Justin Wood