Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Call method on module by String-name

Tags:

I'm pretty new to Elixir and functional programming-languages in general.

In Elixir, I want to call one specific function on Modules, given the Module name as String.

I've got the following (very bad) code working, which pretty much does what I want to:

module_name = elem(elem(Code.eval_file("module.ex", __DIR__), 0), 1)
apply(module_name, :helloWorld, [])

This (at least as I understand it) compiles the (already compiled) module of module.ex in the current directory. I'm extracting the modules name (not as a String, don't know what data-type it actually is) out of the two tuples and run the method helloWorld on it.

There are two problems with this code:

  1. It prints a warning like redefining module Balance. I certainly don't want that to happen in production.

  2. AFAIK this code compiles module.ex. But as module.ex is already compiled and loaded, it don't want that to happen.

I don't need to call methods on these modules by filename, the module-name would be ok too. But it does have to by dynamic, eg. entering "Book" at the command line should, after a check whether the module exists, call the function Book.helloWorld.

Thanks.

like image 867
lschuermann Avatar asked Apr 17 '16 16:04

lschuermann


1 Answers

Well, thats where asking helps: You'll figure it out yourself the minute you ask. ;)

Just using apply(String.to_existing_atom("Elixir.Module"), :helloWorld, []) now. (maybe the name "Module" isn't allowed, don't know)

like image 183
lschuermann Avatar answered Sep 18 '22 12:09

lschuermann