Other Ways to Run Code Fragments
We can use the function Code.eval_quoted to evaluate code fragments, such as those returned by quote.
| iex> fragment = quote do: IO.puts("hello") |
| {{:.,[],[{:__aliases__,[alias: false],[:IO]},:puts]},[],["hello"]} |
| iex> Code.eval_quoted fragment |
| hello |
| {:ok,[]} |
By default, the quoted fragment is hygienic, and so does not have access to variables outside its scope. Using var!(:name), we can disable this feature and allow a quoted block to access variables in the containing scope. In this case, we pass the binding to eval_quoted as a keyword list.
| iex> fragment = quote do: IO.puts(var!(a)) |
| {{:., [], [{:__aliases__, [alias: false], [:IO]}, :puts]}, [], |
| [{:var!, [context: Elixir, ... |
Get Programming Elixir 1.2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.