Ah, I see … You have tried my example to create a top-level module in another module.
First of all you need to understand something … As same as you can check AST with quote do … end as same you can check how modules are “defined” inside using IO.puts(module).
iex> IO.puts(String)
Elixir.String
iex> IO.puts(Example)
Elixir.Example
iex> IO.puts(:opp)
opp
iex> IO.puts(:Opp)
Opp
With this you should understand why sub_field :Opp do … end does not generates Opp module. However it’s easy to do so. Simply add Elixir. prefix instead of :, so:
defmodule MyLib do
defmacro sub_field(name, do: block) do
quote do
defmodule unquote(name) do
unquote(block)
end
end
end
end
defmodule Example do
import MyLib
sub_field Elixir.Opp do
def sample, do: IO.inspect(__MODULE__)
end
end
Opp.sample()
You can also do that within macro using for example Module.concat/2
iex> Module.concat(Elixir, :Opp)
Opp


















