Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Elixir, is there a way to determine if a module exists?

Tags:

elixir

As the title states, my question is:

Is there a way to determine a module exists by its name in Elixir?

After looking around for some time I came around this thread in the Elixir forums but is not exactly what I'm looking for. In this thread they mention Code.ensure_loaded/1, but I don't think it is quite what I need.

Right now I'm approaching the problem with something as follows:

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

But I'm not convinced.

Any help is appreciated, thanks!

like image 250
Daniel Zendejas Avatar asked May 09 '17 23:05

Daniel Zendejas


1 Answers

Usually, we just check to ensure a given function in the module is compiled.

iex(9)> Code.ensure_compiled?(Enum)
true
iex(10)>

You can also check to see if a specific function is definined

ex(10)> function_exported? Enum, :count, 1
true
iex(11)>

EDIT

@Russ Matney as a good point about Code.ensure_compiled?/1 loading the module.

Here is an approach that should work without any side effects:

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

Elixir modules export :__info__/1 so testing for it provides a generic solution.

like image 111
Steve Pallen Avatar answered Oct 14 '22 18:10

Steve Pallen