module - Elixir 重命名并包装 Erlang 模块?

标签 module erlang elixir

是否可以重命名现有的 Erlang 模块?我在几个 Erlang 模块中有一些代码,我想在 Elixir 项目(断言库)中使用。

我不想将所有 Erlang 模块都转换为 Elixir,因为它们是完整的,但我想重命名它们,并可能向它们添加额外的功能。这两个模块都只是函数的集合,它们不实现行为或做任何不寻常的事情。

我希望能够使用现有的 Erlang 模块:

-module(foo_erl).

-export([some_fun/1]).

some_fun(Arg) ->
  ok.

然后编写一个 Elixir 模块来扩展 Erlang 模块:

defmodule ExFoo do
   somehow_extends_erlang_module :foo_erl

   another_fun(arg) do
     :ok
   end
end

然后可以使用 Erlang 模块中定义的函数:

iex(1)> ExFoo.some_fun(:arg) #=> :ok

这在 Elixir 中可行吗?如果是这样,我该怎么做?

最佳答案

这是我可以建议的第一件事。我 100% 确定它可以以更优雅的方式解决。由于我还不是 Elixir 大师,我稍后会回到这个话题。

defmodule Wrapper do
  defmacro __using__(module) do
    exports = module.module_info[:exports] -- [module_info: 0, module_info: 1]
    for {func_name, arity} <- exports do
      args = make_args(arity)
      quote do
        def unquote(func_name)(unquote_splicing(args)) do
          unquote(module).unquote(func_name)(unquote_splicing(args))
        end
      end
    end
  end

  defp make_args(0), do: []
  defp make_args(arity) do
    Enum.map 1..arity, &(Macro.var :"arg#{&1}", __MODULE__)
  end
end

defmodule WrapperTest do
  use ExUnit.Case, async: true

  use Wrapper, :lists

  test "max function works properly" do
    assert (max [1, 2]) == 2
  end
end

关于module - Elixir 重命名并包装 Erlang 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694387/

相关文章:

python - 在 python 中,使用 os.system 调用模块,然后基于该模块调用 python 模块

python - 我是否必须在 python 中重新加载模块才能捕获更改?

iOS CommonJS 模块返回 "undefined is not a constructor"错误

elixir - 谁能准确解释一下Plug.Conn中put_private的含义?

elixir - 列表包含另一个顺序相同的列表

javascript - 为什么在 Javascript 模块模式中使用自执行匿名函数?

erlang - 如何运行基于 Erlang 的机器人?是否可以将其转换为 .hex 并在微 Controller 上运行?

shell - 如何在Linux系统启动时自动启动erl.beam文件?

haskell - 惰性和函数组合(haskell、erlang)

elixir - 在 Elixir 中使用 Erlang 库