Elixir: "warning: redefining module" unproductive for code generation

Created on 5 Feb 2016  路  3Comments  路  Source: elixir-lang/elixir

Whenever a module is redefined using a macro, Elixir emits this warning to stderr:

nofile: warning: redefining module Project.Config

We are using the following pattern to generate modules in runtime for storing our configuration:

defp gen_config(config = %{}) do
  quoted =
    quote do
      defmodule Project.Config do
        unquote(Enum.map(config, fn({key,value}) -> gen_function(key, value) end))
        def get(_any), do: nil
        def get(_any, default), do: default
      end
    end
  Code.compile_quoted(quoted)
  :ok
end

Changing our configuration and updating this module, will trigger this warning. We also use this pattern to generate efficient, custom logging callbacks. There are a couple of scenarios when redefining a module makes sense:

  • Configuration
  • Mocking
  • Caching
  • Logging

And perhaps some others. I would question the value of this warning, as it is something that cannot easily be disabled. I prefer as a programmer not to be questioned in what I do, especially in the case where I am in control and doing something on purpose.

I understand that there is some value in having the warning, but I would rather not have output and logs spammed with it when using the compiler deliberately. Questions:

  1. Would it be possible to remove or disable this warning somehow?
  2. If not, are the pattern we're using somehow wrong? Is there a better way to achieve the same thing that would not yield the warning?

Most helpful comment

Should have dug further, the following solves our problem:

           def get(_any, default), do: default
         end
       end
+    Code.compiler_options(ignore_module_conflict: true)
     Code.compile_quoted(quoted)
     :ok
   end

All 3 comments

Should have dug further, the following solves our problem:

           def get(_any, default), do: default
         end
       end
+    Code.compiler_options(ignore_module_conflict: true)
     Code.compile_quoted(quoted)
     :ok
   end

I would recommend to set it when your application starts.

Well, someone could unset it later since the options are global (ugh!). If there was a way to pass options to each compile call, that would be nicer. :smile:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vothane picture vothane  路  3Comments

ckampfe picture ckampfe  路  3Comments

lukaszsamson picture lukaszsamson  路  3Comments

josevalim picture josevalim  路  3Comments

ghost picture ghost  路  4Comments