Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elixir dynamic module call

How can I call function func() in a module called App.Reporting.Name

based on the string "name" which is not known until runtime

using String.to_atom or to_existing_atom does not work :

 alias App.Reporting.Name
 module = "name" |> String.capitalise |> String.to_atom     
 apply(module, :func, [])

Without the alias, this does not work either

module = "App.Reporting.Name" |> String.to_atom     
apply(module, :func, [])

I get an (UndefinedFunctionError) and (module :"App.Reporting.Name" is not available)

thanks

like image 545
user2725682 Avatar asked Jan 05 '23 20:01

user2725682


1 Answers

Your second approach is almost correct, you just need to prefix Elixir. because App.Reporting.Name is equal to :"Elixir.App.Reporting.Name", not :"App.Reporting.Name" since Elixir prefixes all module names (names starting with an uppercase letter) with Elixir. before turning it into an atom:

iex(1)> App.Reporting.Name == :"App.Reporting.Name"
false
iex(2)> App.Reporting.Name == :"Elixir.App.Reporting.Name"
true

So, this code should work:

module = "Elixir.App.Reporting.Name" |> String.to_atom     
apply(module, :func, [])

and so should this:

module = Module.concat(App.Reporting, "name" |> String.capitalize |> String.to_atom)
apply(module, :func, [])
like image 173
Dogbert Avatar answered Jan 07 '23 10:01

Dogbert