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
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, [])
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