简体   繁体   中英

Elixir Macro issue with unquoting

Can you please have a look at my Macro? I am getting undefined function number/0 error, and I can't figure it out why.

 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

You don't need to unquote number . unquote is used when you want to inject a variable present outside the quote block. Since number is defined inside the quote , you don't need to unquote . The following should work for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM