在elixir中的引号块外定义函数

在elixir中的引号块外定义函数,elixir,metaprogramming,ex-doc,Elixir,Metaprogramming,Ex Doc,我有一个简单的宏,它将函数注入调用模块 defmodule MyModule do defmacro __using__(_opts) do quote do def run do IO.puts "Hello world" end end end end 这可以按预期工作,但由于run函数嵌套在quote块中,因此我无法使用ExDoc添加文档。我还想在外部定义run函数,因为我觉得这样可以使代码看起来更好。大概是这样的: def

我有一个简单的宏,它将函数注入调用模块

defmodule MyModule do
  defmacro __using__(_opts) do
    quote do
      def run do
        IO.puts "Hello world"
      end
    end
  end
end
这可以按预期工作,但由于run函数嵌套在quote块中,因此我无法使用ExDoc添加文档。我还想在外部定义run函数,因为我觉得这样可以使代码看起来更好。大概是这样的:

defmodule MyModule do
  def run do
    IO.puts "Hello world"
  end

  defmacro __using__(_opts) do
    quote do
       # Some code to inject the run function
    end
  end
end

我该怎么做呢?此外,如何使用ExDoc为嵌套函数添加文档?

您可以在
引号中使用
defdelegate
,然后在主模块中定义
run

defmodule MyModule do
  @doc """
  Prints "Hello world"
  """
  def run do
    IO.puts "Hello world"
  end

  defmacro __using__(_opts) do
    quote do
      defdelegate run, to: MyModule
    end
  end
end

defmodule A do
  use MyModule
end
A.run/0
默认情况下将获得自动生成的文档,该文档将用户指向
MyModule.run/0
。如果需要,可以通过在
defdelegate
之前添加一个
@doc”“
来进行自定义

iex(1)> MyModule.run
Hello world
:ok
iex(2)> A.run
Hello world
:ok
iex(3)> h(MyModule.run)

                                   def run()

Prints "Hello world"

iex(4)> h(A.run)

                                   def run()

See MyModule.run/0.

您想将文档添加到MyModule.run中吗?还是希望它出现在您注入到使用MyModule的模块中的
run
函数中?@Dogbert我想将文档添加到MyModule.run中,如果我为嵌套运行定义了文档,则在使用MyModule的模块中函数我在目标模块中获得了文档,但不是原始模块。非常感谢。这是可行的,但是如果run函数有参数怎么办?@MohideenImranKhan如果你说
def add(a,b)…
,那么
defdelegate
将是
defdelegate add(a,b),to:MyModule
@Dogbert谢谢。