Elixir将导入的函数重命名为别名

lap*_*ira 2 elixir

假设我正在测试属于Utils模块的函数

defmodule Test do
  alias Module.Utils

  test "test 1" do
    Utils.some_function?(...)
  end

  test "test 2" do
    Utils.some_function?(...)
  end
end
Run Code Online (Sandbox Code Playgroud)

我可以将该函数重构或简化为:

import Utils.some_function as test_func()
Run Code Online (Sandbox Code Playgroud)

所以我不必编写模块名称并简化函数名称

Dog*_*ert 6

导入时无法重命名函数.

您可以使用defdelegate创建一个本地函数来调用另一个模块的函数,如下所示:

defmodule A do
  def just_add_these_two_numbers(a, b), do: a + b
end

defmodule B do
  defdelegate add(a, b), to: A, as: :just_add_these_two_numbers
  # `add/2` is now the same as `A.just_add_these_two_numbers/2`.

  def test do
    IO.inspect add(1, 2) == 3
  end
end

B.test #=> true
Run Code Online (Sandbox Code Playgroud)

虽然你可能只是这样做(它甚至更短):

def add(a, b), do: A.just_add_these_two_numbers(a, b)
Run Code Online (Sandbox Code Playgroud)