How to disable warning for redefining a constant when loading a file

sawa picture sawa · Feb 11, 2012 · Viewed 15.1k times · Source

Is there a way to disable warning: already initialized constant when loading particular files?

Answer

user2398029 picture user2398029 · Feb 11, 2012

The solution to your problem depends on what is causing it.

1 - You are changing the value of a constant that was set before somewhere in your code, or are trying to define a constant with the same name as an existant class or module. Solution: don't use constants if you know in advance that the value of the constant will change; don't define constants with the same name as class/modules.

2 - You are in a situation where you want to redefine a constant for good reasons, without getting warnings. There are two options.

First, you could undefine the constant before redefining it (this requires a helper method, because remove_const is a private function):

Object.module_eval do
  # Unset a constant without private access.
  def self.const_unset(const)
    self.instance_eval { remove_const(const) }
  end
end

Or, you could just tell the Ruby interpreter to shut up (this suppresses all warnings):

# Runs a block of code without warnings.
def silence_warnings(&block)
  warn_level = $VERBOSE
  $VERBOSE = nil
  result = block.call
  $VERBOSE = warn_level
  result
end

3 - You are requiring an external library that defines a class/module whose name clashes with a new constant or class/module you are creating. Solution: wrap your code inside a top-level module-namespace to prevent the name clash.

class SomeClass; end
module SomeModule
   SomeClass = '...' 
end

4 - Same as above, but you absolutely need to define a class with the same name as the gem/library's class. Solution: you can assign the library's class name to a variable, and then clear it for your later use:

require 'clashing_library'
some_class_alias = SomeClass
SomeClass = nil
# You can now define your own class:
class SomeClass; end
# Or your own constant:
SomeClass = 'foo'