I have a macro that defines a module like so.
defmodule Bar do
def bar do
IO.puts "I am #{inspect __MODULE__}"
end
end
defmodule MacroFun do
defmacro define_module(name) do
quote do
defmodule unquote(name) do
import Bar
def foo do
bar
IO.puts "I am #{inspect __MODULE__}"
end
end
end
end
end
defmodule Runner do
require MacroFun
def run do
MacroFun.define_module Foo
Foo.foo
end
end
Runner.run
The output of running this is:
I am Bar
I am Runner.Foo
Which makes sense; MacroFun.define_module
was called in Runner.run
so the module was defined and thus nested under the Runner
module.
But now if I change MacroFun.define_module
to use the :bind_quoted
option:
defmacro define_module(name) do
quote bind_quoted: [name: name] do
defmodule name do
import Bar
def foo do
bar
IO.puts "I am #{inspect __MODULE__}"
end
end
end
end
The output now becomes:
I am Bar
I am Foo
Why??