Elixir: use a macro in the body of the same module that defined it

This is a common elixir:

defmodule Fizz do
  defmacro asdf, do: IO.puts("asdf")
end

defmodule Buzz do
  require Fizz
  Fizz.asdf
end

However, although you can reference macros in the same context as:

defmodule Fizz do
  # ...
  defmacro asdf_qwer, do: asdf && IO.puts("qwer")
end

... you cannot reference macros in the body of the same module that defined them :

defmodule Fizz do
  defmacro asdf, do: IO.puts("asdf")
  asdf
end

Arises undefined function asdf/0.

Is there a workaround for this "problem"? Sometimes I can use macros to remove some templates from the module I'm working on, and that the macro function can be specific enough not to put it in another module.

+4
source share
1 answer

, undefined function, , asdf .

, .

@after_compile callback , , ,

:

defmodule M do
  @after_compile __MODULE__

  def __after_compile__(env, _bytecode) do
    IO.inspect env
  end
end

- Fizz.Macros.

+1

Source: https://habr.com/ru/post/1649558/


All Articles