Elixir Macro问题与unquoting

时间:2017-11-14 23:52:21

标签: macros elixir

你能看看我的宏吗? 我收到undefined function number/0错误,我无法弄清楚原因。

 defmodule DbUtil do
        defmacro __using__(opts) do
            quote do
              import unquote(__MODULE__)
              @before_compile unquote(__MODULE__)
            end
        end

        defmacro __before_compile__(%{module: definition} = _env) do

            quote do
                import Ecto.Query

                def last do
                    from x in unquote(definition), order_by: [desc: x.id], limit: 1
                end

                # This dumps error
                def limits(number) do
                    from a in unquote(definition), limit: ^unquote(number)
                end
            end

        end
    end

1 个答案:

答案 0 :(得分:2)

您无需unquote number。当您想要注入unquote块之外的变量时,使用quote。由于在number内定义了quote,因此您无需unquote。以下内容适用于您:

def limits(number) do
  from a in unquote(definition), limit: ^number
end