title: How do you create and load modules dynamically at runtime in Elixir, or Erlang?
body: <p>The basic scenario is this:  I need to load text from a database, and then turn that text into an Elixir module (or an Erlang module) and then make calls into it.  The text is effectively the same as a module file. So this is a form of hot code loading.  I want to compile the "file" and then load the resulting module, then make calls into it.  Later I'll unload it. The only difference is the code exists in a database rather than a file on the disk. (and it doesn't exist at the time that I'm writing the code that will be loading it.)</p>
  
  <p>I know Erlang supports hot code loading, but seems focused on compiling files on disk and then loading the beams.  I wish to do this as a more dynamic process, and I won't be replacing running code, but loading the code, then running it, then unloading it.</p>
  
  <p>There are several facilities in Elixir for evaluating code at runtime. I'm trying to figure out how to do this with them, and the documentation is a bit sparse. </p>
  
  <pre><code>Code.compile_string(string, "nofile")
  </code></pre>
  
  <p>"returns a list of tuples where the first element is the module name and the second one is its binary".   So, now I have the modules names and their binaries, but I do not know of a way to then load the binaries into the runtime and call into them.  How would I do that?  (There's no function for that in the Code library that I can see.) </p>
  
  <p>Possibly I could then use the Erlang function:</p>
  
  <pre><code>:code.load_binary(Module, Filename, Binary)  -&gt;
             {module, Module} | {error, What}
  </code></pre>
  
  <p>Ok, so this returns a tuple with the atom "module" and then the Module.  If the string loaded from the database defined a module called "Paris", how in my code would I then execute </p>
  
  <pre><code>paris.handler([parameters])
  </code></pre>
  
  <p>since I don't know in advance that there will be a module called paris?  I could know, by having the string "paris" also stored in the database that this is the name, but is there any way of calling into a module, using a string as the name of the module you're calling?</p>
  
  <p>There is also: </p>
  
  <pre><code>eval(string, binding // [], opts // [])
  </code></pre>
  
  <p>Which evaluates the contents of the string.  Can this string be the entire definition of a module?  It appears not.  I'd like to be able to write this code that's being evaluated in such a way that it has multiple functions that call each other--e.g. a complete little program, with a pre-defined entry point (Which could be a main, such as "DynamicModule.handle([parameter, list])"</p>
  
  <p>Then there's the EEx module, which has:</p>
  
  <pre><code>compile_string(source, options // [])
  </code></pre>
  
  <p>Which is great for doing templates.  But ultimately it only seems to work for the use case where there's a string and you've got Elixir code embedded in it.  It evaluates the string in the context of the options and produces a string.  I'm seeking to compile the string into one or more functions that I can then call.  (If I can only make one function that's fine, that function can pattern match or switch into doing the other things that are needed....)</p>
  
  <p>I know this is unconventional, but I have my reasons for doing it this way and they are good ones.  I'm looking for advice about how to do this, but don't need to be told "don't do that".  It seems like it should be possible, Erlang supports hot code loading and Elixir is pretty dynamic, but I just don't know the syntax, or the right functions.   I'll be monitoring this question closely. Thanks in advance!</p>
  
  <hr>
  
  <p><strong>EDITS based on the first answers:</strong></p>
  
  <p>Thanks for the answers, this is good progress. As Yuri showed, eval can define a module, and as José points out, I can just use code eval for small parts of code with bindings.</p>
  
  <p>The code being evaluated (whether turned into a module, or not) is going to be fairly complex.  And its development would be best involving breaking it down into functions and calling those functions.</p>
  
  <p>To help, let me provide some context.  Assume I'm building a web framework.  The code loaded in from the database is handlers for specific URIs.  So, when an HTTP call comes in, I might load the code for example.com/blog/  This page might involve several different things, such as comments, a list of recent posts, etc.</p>
  
  <p>Since many people are hitting the page at the same time, I'm spawning a process to handle each page view.  Thus there are many times when this code may be evaluated simultaneously, for different requests.</p>
  
  <p>The the module solution allows one to break the code up into functions for different parts of the page (eg: the list of posts, comments, etc. )  And I would load the module once, at startup, and let many processes spawn that call into it.  The module is global, correct? </p>
  
  <p>What happens if there's a module already defined?  EG: When the module changes, and there are processes already calling that module. </p>
  
  <p>In iex, I am able to redefine a module that's already been defined:</p>
  
  <pre><code>iex(20)&gt; Code.eval "defmodule A do\ndef a do\n5\nend\nend"
  nofile:1: redefining module A
  </code></pre>
  
  <p>What happens if I redefine the module at runtime, to all the processes currently calling into that module?   Also, will this redefinition work outside of iex, in normal operation?</p>
  
  <p>Assuming that redefining the module would be problematic, and that modules being global might run into problems with namespace collisions, I looked into using eval to define a function.</p>
  
  <p>If I can merely have the code from the database define functions, then those functions are within the scope of whatever process, and we don't have the possibility of global collisions. </p>
  
  <p>However, this doesn't seem to work:</p>
  
  <pre><code>iex(31)&gt; q = "f = function do
  ...(31)&gt; x, y when x &gt; 0 -&gt; x+y
  ...(31)&gt; x, y -&gt; x* y
  ...(31)&gt; end"
  "f = function do\nx, y when x &gt; 0 -&gt; x+y\nx, y -&gt; x* y\nend"
  iex(32)&gt; Code.eval q
  {#Fun&lt;erl_eval.12.82930912&gt;,[f: #Fun&lt;erl_eval.12.82930912&gt;]}
  iex(33)&gt; f
  ** (UndefinedFunctionError) undefined function: IEx.Helpers.f/0
      IEx.Helpers.f()
      erl_eval.erl:572: :erl_eval.do_apply/6
      src/elixir.erl:110: :elixir.eval_forms/3
      /Users/jose/Work/github/elixir/lib/iex/lib/iex/loop.ex:18: IEx.Loop.do_loop/1
  
  iex(33)&gt; f.(1,3)
  ** (UndefinedFunctionError) undefined function: IEx.Helpers.f/0
      IEx.Helpers.f()
      erl_eval.erl:572: :erl_eval.do_apply/6
      erl_eval.erl:355: :erl_eval.expr/5
      src/elixir.erl:110: :elixir.eval_forms/3
      /Users/jose/Work/github/elixir/lib/iex/lib/iex/loop.ex:18: IEx.Loop.do_loop/1
  </code></pre>
  
  <p>I also tried: </p>
  
  <pre><code>    iex(17)&gt; y = Code.eval "fn(a,b) -&gt; a + b end"
  {#Fun&lt;erl_eval.12.82930912&gt;,[]}
  iex(18)&gt; y.(1,2)
  ** (BadFunctionError) bad function: {#Fun&lt;erl_eval.12.82930912&gt;,[]}
      erl_eval.erl:559: :erl_eval.do_apply/5
      src/elixir.erl:110: :elixir.eval_forms/3
      /Users/jose/Work/github/elixir/lib/iex/lib/iex/loop.ex:18: IEx.Loop.do_loop/1
  </code></pre>
  
  <p>So, in summary:</p>
  
  <ol>
  <li><p>Can modules be redefined using Code.eval when there are processes calling into them?</p></li>
  <li><p>Is it possible to use Code.eval to make functions whose scope is bound to the process in which Code.eval was called? </p></li>
  <li><p>If you understand what it is I'm trying to do, can you suggest a better way to go about it? </p></li>
  </ol>
  
  <p>Also, if there is a better forum where I should be asking this, feel free to let me know.  And if there are docs or relevant examples I should read, please feel free to point me to them.  I'm not trying to get you to do all the work, I just am unable to figure it out myself. </p>
  
  <p>I'm learning Elixir specifically for the ability to dynamically evlauate code, but my Elixir knowledge is minimal now- I just started- and my erlang is rusty too. </p>
  
  <p>Much thanks!</p>