Providing hints to prevent unused alias warnings from macros

I’ve created a configuration module inspired by Saša Jurić’s approach at The Erlangelist - Rethinking app env

It looks a bit like this:

defmodule MyConfig do

  defmacro __using__([]) do
    quote do
      import MyConfig, only: [env_specific: 1]
    end
  end

  defmacro env_specific(config) do
    quote do
      unquote(
        Keyword.get_lazy(
          config,
          Mix.env(),
          fn -> Keyword.fetch!(config, :else) end
        )
      )
    end
  end
end

And then my usage module might look like this:

defmodule Usage do

  use MyConfig

  alias MyApp.{MyClient, MyClientMock}

  def client, do: env_specific(
    test: MyClientMock,
    else: MyClient
  )
end

The code works perfectly well (and thank you to Saša for the approach!). However, I get a warning when compiling that either MyClient or MyClientMock aliases are unused, depending on which environment I’m working in.

I understand why the warning is occurring - it’s true that only one of these aliases is ever used at a time, but in this case that’s by design. Is there a way that I can provide some sort of hint to the compiler that this is intentional?

2 Likes

Yet again seconds after posting I find the answer on this forum:

The approach I’ve opted for so far is to add warn: false to my alias directive.

1 Like