Hi! I’m playing around with macros but I got stuck deduplicating a piece of code.
defmodule SomeMap do
def load(file_path) do
file_path
|> File.read!()
|> Jason.decode!()
end
defmacro __using__(file_path) do
quote do
@map unquote(Macro.escape(load(file_path)))
def load(file_path) do
unquote(&load/1)(file_path)
end
end
end
end
As you can see, in this example I want to use load
for two things, loading some map into an attribute at compile time, and also insert the function into the using module so that I can load the same thing at runtime. I’ve tried many variations of it, but eg this version errors with Compilation Error: invalid call #Function<0.85068536/1 in SomeSchema."MACRO-__using__"/2>(file_path)
.
Disclaimer: this is for learning, I realise I could do this without a macro.