11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マクロ展開後のコードを見る

Posted at

ブログから整形して転載。

マクロが自分が望んだ形に展開されているかテストする方法。

# lib/my_module.ex

defmodule MyModule do
  defmacro my_macro do  # テスト対象
    quote do
      ...  # 略
    end
  end
end
# test/test_helper.exs

ExUnit.start

defmodule TestHelper do
  defmacro macro_to_code(macro) do
    macro |> Macro.expand(__CALLER__) |> Macro.to_string
  end
end
# test/my_module_test.exs

defmodule MyModuleTest do
  use ExUnit.Case
  import TestHelper

  test "my_macro" do
    expanded = macro_to_code(MyModule.my_macro)  # 文字列が返る
    assert expanded =~ ~r/.../
  end
end

以下のようにすると、文字列ではなくASTが返ります。

defmacro macro_to_ast(macro) do
  macro |> Macro.expand(__CALLER__) |> Macro.escape
end
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?