2

我正在使用宏,我想将动态标识符传递给 Absinthe 宏enum,希望enum使用集合列表生成不同的 s。一切都在for理解之中。

我读过这Kernel.apply/3不适用于宏。

  1. 我也试过:
   for name <- [:hello, :world] do
       enum  unquote(name) do
          value(:approved)
       end  
   end

结果得到:

** (ArgumentError) argument error
   :erlang.atom_to_binary({:unquote, [line: 36], [{:name, [line: 36], nil}]}, :utf8)
  1. 我也试过不加引号:
   for name <- [:hello, :world] do
      enum name do
        value(:approved)
      end
   end

并得到:

** (ArgumentError) argument error
   :erlang.atom_to_binary({:name, [line: 36], nil}, :utf8)

似乎我无法取消引用我作为宏标识符传递的任何内容enum。是否有可能做到这一点?

4

1 回答 1

3

有可能的。问题是enum假设第一个参数是一个原子。

defmodule MacroHelper do

  defmacro enum_wrapper(names, do: block) do
    for name <- names do
      quote do
        enum unquote(name), do: unquote(block)
      end
    end
  end

end

defmodule AbsDemo do

  use Absinthe.Schema.Notation
  import MacroHelper

  enum_wrapper [:hello, :world] do
    value :approved
  end

end
于 2019-04-04T03:42:23.163 回答