Throw an exception when reassigning a constant in Ruby?

I have long known that “constants” in Ruby (that is, variable names that are uppercase) are not really constant. Like other programming languages, an object reference is the only thing stored in a variable / constant. (Sidebar: Ruby has the ability to “freeze” objects referenced by objects that, as far as I know, are not an ability offered in many other languages.)

So here is my question: when you reassign a value to a constant, you get a warning like this:

>> FOO = 'bar'
=> "bar"
>> FOO = 'baz'
(irb):2: warning: already initialized constant FOO
=> "baz"

Is there a way to get Ruby to throw an exception instead of printing a warning? It is difficult to understand why reassignments sometimes occur.

+5
source share
3 answers

Look at this question to find out how warnings can be treated as errors in some cases.

Otherwise, I think you will have to write your own method for assigning constants and raise an exception if it is already assigned.

If you know that the reassignment happens with a certain constant, you can also add a health check immediately before the assignment.

+5
source

You cannot intercept it directly, no.

, . IO -. write , ; "warning: already initialized constant", , write.

+3

, freeze :

# Normal scenario
$VERBOSE = true
class Foo
  BAR = 1
end

Foo::BAR = 2 # warning: already initialized constant BAR
# Using freeze
Foo.freeze
Foo::BAR = 3
RuntimeError: can't modify frozen Class
    from (irb):8
    from /Users/agrimm/.rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>'

Object, .

0

All Articles