Code injection using evaluation
Now that we understand how Code.eval_quoted/3
works, we can use that function to inject behavior into a module from another module.
The following is a module that defines a function that returns a quoted literal. The quoted literal, when evaluated, further defines a hello
function inside the module it is evaluated in. The function is defined as a simple hello
world
function:
behavior_injector.ex
defmodule BehaviorInjector do def behaviour_quoted_expr do quote do def hello, do: IO.puts "Hello world!" end end end
Now, let’s use the previously defined module’s function inside another module:
test_subject.ex
defmodule TestSubject do Code.eval_quoted(BehaviorInjector.behaviour_quoted_expr(), [], __ENV__) end
In the preceding code snippet, we need to provide __ENV__
in order to pass compile-time...