Skip to content

Instantly share code, notes, and snippets.

@bcardarella
Last active August 16, 2025 13:55
Show Gist options
  • Save bcardarella/78faf2958ae1ec0d1dc997420ad10984 to your computer and use it in GitHub Desktop.
Save bcardarella/78faf2958ae1ec0d1dc997420ad10984 to your computer and use it in GitHub Desktop.
Macro.compile_apply wtf

Macro.compile_apply/4

Section

defmodule Foo do
  defmacro __using__(_) do
    Module.register_attribute(__CALLER__.module, :foo, persist: true)
    Module.put_attribute(__CALLER__.module, :foo, :bar)

    quote do
      def test do
        :test
      end
    end
  end
end
defmodule Bar do
  require Foo
  
  defmacro use_foo do
    {:ok, env} = Macro.Env.define_require(__CALLER__, [line: 0], Foo)
    Macro.Env.required?(env, Foo) |> IO.inspect(label: "Required?")
    Macro.compile_apply(Foo, :__using__, [[]], __CALLER__)
  end
end
defmodule Baz do
  require Foo
  require Bar
  Bar.use_foo
end

Baz.__info__(:attributes) |> Keyword.get(:foo) |> IO.inspect()
Baz.test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment