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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With