In Elixir, is there a way to determine if a module exists?
elixir
Solution
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.
Problem
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!