在Elixir中,有没有办法确定模块是否存在?

Dan*_*jas 8 elixir

正如标题所述,我的问题是:

有没有办法确定Elixir中名称存在的模块?

在环顾四周后,我在Elixir论坛中遇到了这个帖子,但并不完全是我正在寻找的.在这个帖子中他们提到Code.ensure_loaded/1,但我认为这不是我需要的.

现在我正在通过以下方式解决问题:

def module_exists?(module_name) where is_atom(module_name) do
  !is_nil(module_name.module_info)
rescue
  e in UndefinedFunctionError -> false
end
Run Code Online (Sandbox Code Playgroud)

但我不相信.

任何帮助表示赞赏,谢谢!

Ste*_*len 15

通常,我们只是检查以确保编译模块中的给定函数.

iex(9)> Code.ensure_compiled?(Enum)
true
iex(10)>
Run Code Online (Sandbox Code Playgroud)

您还可以检查是否确定了特定功能

ex(10)> function_exported? Enum, :count, 1
true
iex(11)>
Run Code Online (Sandbox Code Playgroud)

编辑

@Russ Matney是关于Code.ensure_compiled?/1加载模块的一个好点.

这是一种应该没有任何副作用的方法:

defmodule Utils do
  def module_compiled?(module) do
    function_exported?(module, :__info__, 1)
  end
end

iex> Utils.module_compiled?(String)
true
iex> Utils.module_compiled?(NoModule)
false
Run Code Online (Sandbox Code Playgroud)

Elixir模块导出,:__info__/1因此对其进行测试可提供通用解决方案.

  • 请注意这里的一个副作用:“Code.ensure_compiled?/1”也会尝试加载模块(如果尚未加载),这可能是不需要的(取决于用例)。 (3认同)