Was talking with ChatGPT, is the following code a valid/good replacement for Code.eval_string?
def create_function(name, args, code) do
ast = Macro.escape(code, [:strict])
code = Macro.to_string(ast)
{name, Code.string_to_quoted(code)}
end
This code would run in a template engine of sorts to load function schema/definitions from a json file.
defmodule Engine do
def start(schema_files) do
functions =
schema_files
|> Enum.map(&parse_schema_file/1)
|> Enum.map(&create_function/1)
|> Map.new
# Store the functions in the `functions` map
Process.put(:functions, functions)
end
end
ChatGPT explanation:
In this example, the Macro.escape/2 function is used to compile the code string into an AST. The :strict option is passed as the second argument to Macro.escape to ensure that the code is compiled in strict mode, which means that all variables must be declared before they are used. The Macro.to_string/1 function is then used to convert the AST back into a string of Elixir code. Finally, the Code.string_to_quoted/1 function is used to parse the code string and return a tuple containing the function name and the function itself.
This approach has the advantage of being more efficient than Code.eval_string, since the code is only compiled once and then stored as a quoted expression, rather than being compiled every time it is called. It also has the advantage of being safer than Code.eval_string, since it does not allow arbitrary code to be executed. However, it is a bit more complex to use and requires a deeper understanding of Elixir’s macro system.


















