hello everyone.
I am trying to learn metaprogramming and start with simple project. in this road I this weird situation.
I want to implement interface like action_fallback
macro in Phoenix controller(inside UseSample
module).
defmodule GuardModule do
def test() do
IO.inspect("TEST")
end
end
defmodule Sample do
defmacro guard(module_name) do
quote do
@guard unquote(module_name)
end
end
defmacro __using__(_opts) do
quote do
import unquote(__MODULE__)
Module.register_attribute(__MODULE__, :guard, accumulate: :false, persist: :false)
@before_compile unquote(__MODULE__)
end
end
defmacro __before_compile__(env) do
custom_guard = Module.get_attribute(env.module, :guard)
custom_guard.test()
# quote do
# def test_inside_use_sample() do
# custom_guard.test()
# end
# end
end
end
defmodule UseSample do
use Sample
guard GuardModule
end
now I have some questions.
- in
Sample.__before_compile__
macro i can call external module functions. but i can’t generate function that call this external function inside its body(commented section not compile). how can I do that? - in this situation
GuardModule
compiles before others because it’s in the beginning of file. how can I force elixir compiler to compile this module beforeSample
module? - and finally am i have right solving strategy for this problem or should do something else?
thanks a lot.