Auto-discovering plugin modules in an Elixir project

I had a set of small “fixer” modules, each correcting a distinct kind of bad data in an import. The problem was that I had to hardcode the full list of these modules somewhere in the app. And that list had to be updated every time a new module was added.

Turns out there’s a better way. If this modules follow a certain pattern in a module name, we can autodetect and autoload them at runtime.

The application already knows all its modules: the compiled .app file lists them, and you can read that list:

Application.spec(:my_app, :modules)
# same as :application.get_key(:my_app, :modules)

All we need to do is to drop a new file into lib/my_app/fixers/ and filter modules by namespace at runtime:

defmodule MyApp.Plugins do
  def in_namespace(namespace) do
    prefix = "Elixir.#{namespace}."

    Application.spec(:my_app, :modules)
    |> Enum.filter(&String.starts_with?(Atom.to_string(&1), prefix))
    |> Enum.sort()
  end
end

"MyApp.Fixers"
|> MyApp.Plugins.in_namespace()
|> Enum.reduce(record, fn fixer, acc -> fixer.fix(acc) end)

A couple of gotchas:

  • The order isn’t guaranteed. If the fixers depend on each other, or one should run last as a fallback, sort the list or make the order explicit. Don’t rely on the order in the .app file.
  • Modules may not be loaded yet. In dev and test environments the VM loads modules lazily, so function_exported?(mod, :fix, 1) returns false for a module nobody has called yet. Call Code.ensure_loaded(mod) first.

Another approach is to filter by the behaviour the module declares instead of by its name:

Enum.filter(modules, fn mod ->
  # module_info/1 loads the module if needed; each @behaviour adds a list
  mod.module_info(:attributes)
  |> Keyword.get_values(:behaviour)
  |> List.flatten()
  |> Enum.member?(MyApp.Fixer)
end)

Bonus: discovering functions in a module

The same idea works at the module level. I had a module of zero-arity functions, one per color palette. To pick one at random without listing them twice:

 MyApp.Palettes.__info__(:functions) 
 |> Keyword.keys() 
 |> Enum.random()

Adding a palette now is just adding a function.

← All notes