Search code examples
elixir

How to monkeypatch module function in Elixir


I have an Elixir module that imports some functions. I would like to monkeypatch one of those functions with my own. Is that possible? How would I do this?

UPDATE WITH EXAMPLE

The specific example I have is that for task Mix.Tasks.Deps.Compile, I would like to add some functionality to the 'compile' function.

https://github.com/elixir-lang/elixir/blob/master/lib/mix/lib/mix/tasks/deps.compile.ex

The Mix.Tasks.Deps.Compile module is fairly deeply entrenched into the Mix framework. I would like to make the minimum change, while adding in the extra functionality I want. The functionality I want to add is another condition to the cond do block.


Solution

  • The simple answer is: you can't. There's no notion of monkey patching on the BEAM.

    The longer answer is that modules in BEAM are lazily loaded, so you could replace a module with your own implementation of it (but whole module, not just a single function). But I'm really not sure that's the right way to go for it.