Is there a guide for relying on optional dependencies in a library?

I’m working on a library and I’d like to include a check on if an optional dependency has been included. The easy part is adding {:some_dependency, "~> 1.0", optional: true} but after that it would be nice to have a (preferably official) guide. It seems like in your code you would have Code.ensure_loaded?(SomeDependencyModule) where SomeDependencyModule is a module that you know exists from :some_dependency.

However if you use Code.ensure_loaded? to optionally compile a module or function, your code will not get recompiled automatically if that dependency is later added to the top-level project, is there a way around that?

3 Likes

Does anyone have any ideas on this?

1 Like

Maybe this could be opened as an issue with mix? When a dependency A’s optional dependency B is added/removed/updated, A should probably be recompiled altogether, no?

Apart from using :code.is_loaded I really can’t think of anything.

This is the best “guide” I’ve been able to find on this, which is to use Code.ensure_loaded?/1 with a module that you expect will be inside the optional dependency:

And one example of that approach being used is in Dataloader:

Although there’s no way to know for sure what a module will be in any given dependency, but generally there is a module that corresponds to the application name so this isn’t a large problem in practice.

4 Likes