Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Elixir module exports a specific function

Tags:

elixir

How do you check if an Elixir module has exposed a specific public method? How do you check if the function has been exposed with a specific arity?

Doesn't work:

  • Map.methods
  • Map.functions
  • Map.has_function(:keys)
like image 798
Sheharyar Avatar asked Oct 12 '16 20:10

Sheharyar


2 Answers

Building on the answer here and forum discussion here, there are a few ways to do it:


Check if Function exists for Module

You can check if the function name is present as a key in Map.__info__(:functions)

module = Map
func   = :keys

Keyword.has_key?(module.__info__(:functions), func)
# => true

Check if Function exists with specific arity

To check with arity, we can use Kernel.function_exported?/3:

Kernel.function_exported?(Map, :keys, 1)         # => true
Kernel.function_exported?(Map, :keys, 2)         # => false

Updated to use function from the Kernel module instead of the :erlang module

like image 170
Sheharyar Avatar answered Nov 09 '22 01:11

Sheharyar


Use Kernel.function_exported?/3 like this:

function_exported?(List, :to_string, 1)
# => true
like image 32
balexand Avatar answered Nov 09 '22 00:11

balexand