View Source application_module

The Application Module serves as a utility library designed to facilitate the creation of modules that conform to a specific behavior. Additionally, it allows for the behavior implementation to be managed through the application's configuration settings. This library is particularly useful when paired with testing libraries like Mox or Hammox, as it helps eliminate the boilerplate code often required to retrieve the module ID from the application environment.

The following is an exampmle of an application module:

defmodule MyApplication.Module do
  use Application.Module

  defbehaviour do
    @callback say_hello(name :: String.t()) :: String.t()
  end

  defimplementation do
    def say_hello(name) do
      "Hello, #{name}!"
    end
  end
end

Application.Module implements each of the behaviour functions in MyApplication.Module. Unless overriden by the application's configuration [:my_application, :modules, :module], the functions will delegate the execution to the implementations in the module MyApplication.Module.Implementation, which is automatically generated by Application.Module with the body of the defimplementation block.

When used in companion with a mocking library like Mox, you can easily mock the module's implementation in your tests:

Mox.defmock(MyApplication.Module.Mock, for: MyApplication.Module.Behaviour)
Application.put_env(:my_application, :modules, [module: MyApplication.Module.Mock])

Note: That the naming of the modules and the key of the module under the application's configuration is conventional.

Installation

If available in Hex, the package can be installed by adding application_module to your list of dependencies in mix.exs:

def deps do
  [
    {:application_module, "~> 0.1.0"}
  ]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/application_module.