How can I get main application module namespace from a hex package added as a phoenix project dependency?

Hello I’m trying to write my first hex package for I will be able to reuse it easily in several projects.

I know I can set the module name in question with config file, but I would like to set at least a default value in the hex package config.

For example if the phoenix project main app name is :myapp I would like to call by default (if any config is not set) the module MyappWeb.ErrorHelpers.

Is there a way to do that ?

Congratulations on your first package!

I think that injecting your package into the namespace of another application is probably not a good idea for a few reasons:

  1. There is no strong concept of a “main application” in OTP
  2. You risk namespace clashes (can you guarantee that MyAppWeb.ErrorHelpers doesn’t exist?)
  3. It looks a but like magic - when errors arise it becomes harder to identify the source

I would suggest you “claim” your own namespace and then in your documentation recommend alias ing your module into the relevant application namespace.

4 Likes

I get it, thanks for this explanation.
I will cheat a bit on following library that does pretty much the same thing as my hex package.

@error_message """
    Missing translate_error_module config. Add the following to your config/config.exe
    config :formulator, translate_error_module: YourAppName.Gettext
  """

  defp translate_error(error) do
    if module = Application.get_env(:formulator, :translate_error_module) do
      module.translate_error(error)
    else
      raise ArgumentError, message: @error_message
    end
  end