Hey folks.
I’ve got a simple use case for macros based on the following example module:
defmodule StructTestWorking do
defmodule State do
defstruct []
end
def foo(%State{}), do: nil
end
I want to extract the function foo into a “template module” and then use that module:
defmodule StructTestCommonUsing do
defmacro __using__(_opts) do
quote do
def foo(%State{}), do: nil
end
end
end
defmodule StructTestFailingUsing do
defmodule State do
defstruct []
end
use StructTestCommonUsing
end
As the module name suggests, this doesn’t work. I’m getting this compilation error:
== Compilation error on file lib/struct_test_failing_using.ex ==
** (CompileError) lib/struct_test_failing_using.ex:14: State.__struct__/0 is undefined, cannot expand struct State
(stdlib) lists.erl:1353: :lists.mapfoldl/3
It doesn’t work when using a @before_compile hook either:
defmodule StructTestCommonBeforeCompile do
defmacro __using__(_opts) do
quote do
@before_compile unquote(__MODULE__)
end
end
defmacro __before_compile__(_env) do
quote do
def foo(%State{}), do: nil
end
end
end
defmodule StructTestFailingBeforeCompile do
defmodule State do
defstruct []
end
use StructTestCommonBeforeCompile
end
This is using Elixir v1.3.1. Would you expect this to work?
I’ve also pushed the code to a repo – https://github.com/alco/struct_test.


















