redefining some constant in Ruby (ex. FOO = 'bar') generates the warning already initialized constant.
I’m trying to write a sort of ReallyConstants module, where this code should have this behaviour:
ReallyConstants.define_constant(:FOO, 'bar') #=> sets the constant ReallyConstants::FOO to 'bar'
ReallyConstants::FOO #=> 'bar'
ReallyConstants::FOO = 'foobar' #=> this should raise an Exception
that is, constant redefinition should generate an exception.
Is that possible?
Just scope your constant within a module and then use
Module#freezeto prohibit further modification of the module.E.g.
Note that this doesn’t speak to the mutability of the value assigned to the constant. For that, use
Object#freeze.This approach will bite you hard in environments where your code is reloaded, like in a Rails application. There, you’ll have to jump through an additional hoop, checking whether the module has been defined yet before defining it.
Generally, defensive programming in Ruby is more trouble than it’s worth. What’s your concern?